Client.cpp 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  1. #include "StdInc.h"
  2. #include "Client.h"
  3. #include <SDL.h>
  4. #include "CMusicHandler.h"
  5. #include "../lib/mapping/CCampaignHandler.h"
  6. #include "../CCallback.h"
  7. #include "../lib/CConsoleHandler.h"
  8. #include "CGameInfo.h"
  9. #include "../lib/CGameState.h"
  10. #include "CPlayerInterface.h"
  11. #include "../lib/StartInfo.h"
  12. #include "../lib/BattleState.h"
  13. #include "../lib/CModHandler.h"
  14. #include "../lib/CArtHandler.h"
  15. #include "../lib/CGeneralTextHandler.h"
  16. #include "../lib/CHeroHandler.h"
  17. #include "../lib/CTownHandler.h"
  18. #include "../lib/CBuildingHandler.h"
  19. #include "../lib/spells/CSpellHandler.h"
  20. #include "../lib/serializer/CTypeList.h"
  21. #include "../lib/serializer/Connection.h"
  22. #include "../lib/serializer/CLoadIntegrityValidator.h"
  23. #ifndef VCMI_ANDROID
  24. #include "../lib/Interprocess.h"
  25. #endif
  26. #include "../lib/NetPacks.h"
  27. #include "../lib/VCMI_Lib.h"
  28. #include "../lib/VCMIDirs.h"
  29. #include "../lib/mapping/CMap.h"
  30. #include "../lib/JsonNode.h"
  31. #include "mapHandler.h"
  32. #include "../lib/CConfigHandler.h"
  33. #include "CPreGame.h"
  34. #include "battle/CBattleInterface.h"
  35. #include "../lib/CThreadHelper.h"
  36. #include "../lib/CScriptingModule.h"
  37. #include "../lib/registerTypes/RegisterTypes.h"
  38. #include "gui/CGuiHandler.h"
  39. #include "CMT.h"
  40. extern std::string NAME;
  41. #ifndef VCMI_ANDROID
  42. namespace intpr = boost::interprocess;
  43. #endif
  44. /*
  45. * Client.cpp, part of VCMI engine
  46. *
  47. * Authors: listed in file AUTHORS in main folder
  48. *
  49. * License: GNU General Public License v2.0 or later
  50. * Full text of license available in license.txt file, in main folder
  51. *
  52. */
  53. template <typename T> class CApplyOnCL;
  54. class CBaseForCLApply
  55. {
  56. public:
  57. virtual void applyOnClAfter(CClient *cl, void *pack) const =0;
  58. virtual void applyOnClBefore(CClient *cl, void *pack) const =0;
  59. virtual ~CBaseForCLApply(){}
  60. template<typename U> static CBaseForCLApply *getApplier(const U * t=nullptr)
  61. {
  62. return new CApplyOnCL<U>;
  63. }
  64. };
  65. template <typename T> class CApplyOnCL : public CBaseForCLApply
  66. {
  67. public:
  68. void applyOnClAfter(CClient *cl, void *pack) const override
  69. {
  70. T *ptr = static_cast<T*>(pack);
  71. ptr->applyCl(cl);
  72. }
  73. void applyOnClBefore(CClient *cl, void *pack) const override
  74. {
  75. T *ptr = static_cast<T*>(pack);
  76. ptr->applyFirstCl(cl);
  77. }
  78. };
  79. template <> class CApplyOnCL<CPack> : public CBaseForCLApply
  80. {
  81. public:
  82. void applyOnClAfter(CClient *cl, void *pack) const override
  83. {
  84. logGlobal->errorStream() << "Cannot apply on CL plain CPack!";
  85. assert(0);
  86. }
  87. void applyOnClBefore(CClient *cl, void *pack) const override
  88. {
  89. logGlobal->errorStream() << "Cannot apply on CL plain CPack!";
  90. assert(0);
  91. }
  92. };
  93. static CApplier<CBaseForCLApply> *applier = nullptr;
  94. void CClient::init()
  95. {
  96. hotSeat = false;
  97. connectionHandler = nullptr;
  98. pathInfo = nullptr;
  99. applier = new CApplier<CBaseForCLApply>;
  100. registerTypesClientPacks1(*applier);
  101. registerTypesClientPacks2(*applier);
  102. IObjectInterface::cb = this;
  103. serv = nullptr;
  104. gs = nullptr;
  105. erm = nullptr;
  106. terminate = false;
  107. }
  108. CClient::CClient(void)
  109. {
  110. init();
  111. }
  112. CClient::CClient(CConnection *con, StartInfo *si)
  113. {
  114. init();
  115. newGame(con,si);
  116. }
  117. CClient::~CClient(void)
  118. {
  119. delete applier;
  120. }
  121. void CClient::waitForMoveAndSend(PlayerColor color)
  122. {
  123. try
  124. {
  125. setThreadName("CClient::waitForMoveAndSend");
  126. assert(vstd::contains(battleints, color));
  127. BattleAction ba = battleints[color]->activeStack(gs->curB->battleGetStackByID(gs->curB->activeStack, false));
  128. if(ba.actionType != Battle::CANCEL)
  129. {
  130. logNetwork->traceStream() << "Send battle action to server: " << ba;
  131. MakeAction temp_action(ba);
  132. sendRequest(&temp_action, color);
  133. }
  134. return;
  135. }
  136. catch(boost::thread_interrupted&)
  137. {
  138. logNetwork->debugStream() << "Wait for move thread was interrupted and no action will be send. Was a battle ended by spell?";
  139. return;
  140. }
  141. catch(...)
  142. {
  143. handleException();
  144. return;
  145. }
  146. logNetwork->errorStream() << "We should not be here!";
  147. }
  148. void CClient::run()
  149. {
  150. setThreadName("CClient::run");
  151. try
  152. {
  153. while(!terminate)
  154. {
  155. CPack *pack = serv->retreivePack(); //get the package from the server
  156. if (terminate)
  157. {
  158. vstd::clear_pointer(pack);
  159. break;
  160. }
  161. handlePack(pack);
  162. }
  163. }
  164. //catch only asio exceptions
  165. catch (const boost::system::system_error& e)
  166. {
  167. logNetwork->errorStream() << "Lost connection to server, ending listening thread!";
  168. logNetwork->errorStream() << e.what();
  169. if(!terminate) //rethrow (-> boom!) only if closing connection was unexpected
  170. {
  171. logNetwork->errorStream() << "Something wrong, lost connection while game is still ongoing...";
  172. throw;
  173. }
  174. }
  175. }
  176. void CClient::save(const std::string & fname)
  177. {
  178. if(gs->curB)
  179. {
  180. logNetwork->errorStream() << "Game cannot be saved during battle!";
  181. return;
  182. }
  183. SaveGame save_game(fname);
  184. sendRequest((CPackForClient*)&save_game, PlayerColor::NEUTRAL);
  185. }
  186. void CClient::endGame(bool closeConnection /*= true*/)
  187. {
  188. //suggest interfaces to finish their stuff (AI should interrupt any bg working threads)
  189. for (auto& i : playerint)
  190. i.second->finish();
  191. // Game is ending
  192. // Tell the network thread to reach a stable state
  193. if (closeConnection)
  194. stopConnection();
  195. logNetwork->infoStream() << "Closed connection.";
  196. GH.curInt = nullptr;
  197. {
  198. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  199. logNetwork->infoStream() << "Ending current game!";
  200. if(GH.topInt())
  201. {
  202. GH.topInt()->deactivate();
  203. }
  204. GH.listInt.clear();
  205. GH.objsToBlit.clear();
  206. GH.statusbar = nullptr;
  207. logNetwork->infoStream() << "Removed GUI.";
  208. vstd::clear_pointer(const_cast<CGameInfo*>(CGI)->mh);
  209. vstd::clear_pointer(gs);
  210. logNetwork->infoStream() << "Deleted mapHandler and gameState.";
  211. LOCPLINT = nullptr;
  212. }
  213. playerint.clear();
  214. battleints.clear();
  215. callbacks.clear();
  216. battleCallbacks.clear();
  217. CGKeys::reset();
  218. CGMagi::reset();
  219. CGObelisk::reset();
  220. logNetwork->infoStream() << "Deleted playerInts.";
  221. logNetwork->infoStream() << "Client stopped.";
  222. }
  223. #if 1
  224. void CClient::loadGame(const std::string & fname, const bool server, const std::vector<int>& humanplayerindices, const int loadNumPlayers, int player_, const std::string & ipaddr, const std::string & port)
  225. {
  226. PlayerColor player(player_); //intentional shadowing
  227. logNetwork->infoStream() << "Loading procedure started!";
  228. std::string realPort;
  229. if(settings["testing"]["enabled"].Bool())
  230. realPort = settings["testing"]["port"].String();
  231. else if(port.size())
  232. realPort = port;
  233. else
  234. realPort = boost::lexical_cast<std::string>(settings["server"]["port"].Float());
  235. CServerHandler sh;
  236. if(server)
  237. sh.startServer();
  238. else
  239. serv = sh.justConnectToServer(ipaddr, realPort);
  240. CStopWatch tmh;
  241. std::unique_ptr<CLoadFile> loader;
  242. try
  243. {
  244. boost::filesystem::path clientSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::CLIENT_SAVEGAME));
  245. boost::filesystem::path controlServerSaveName;
  246. if (CResourceHandler::get("local")->existsResource(ResourceID(fname, EResType::SERVER_SAVEGAME)))
  247. {
  248. controlServerSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::SERVER_SAVEGAME));
  249. }
  250. else// create entry for server savegame. Triggered if save was made after launch and not yet present in res handler
  251. {
  252. controlServerSaveName = boost::filesystem::path(clientSaveName).replace_extension(".vsgm1");
  253. CResourceHandler::get("local")->createResource(controlServerSaveName.string(), true);
  254. }
  255. if(clientSaveName.empty())
  256. throw std::runtime_error("Cannot open client part of " + fname);
  257. if(controlServerSaveName.empty() || !boost::filesystem::exists(controlServerSaveName))
  258. throw std::runtime_error("Cannot open server part of " + fname);
  259. {
  260. CLoadIntegrityValidator checkingLoader(clientSaveName, controlServerSaveName, MINIMAL_SERIALIZATION_VERSION);
  261. loadCommonState(checkingLoader);
  262. loader = checkingLoader.decay();
  263. }
  264. logNetwork->infoStream() << "Loaded common part of save " << tmh.getDiff();
  265. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  266. const_cast<CGameInfo*>(CGI)->mh->map = gs->map;
  267. pathInfo = make_unique<CPathsInfo>(getMapSize());
  268. CGI->mh->init();
  269. logNetwork->infoStream() <<"Initing maphandler: "<<tmh.getDiff();
  270. }
  271. catch(std::exception &e)
  272. {
  273. logGlobal->errorStream() << "Cannot load game " << fname << ". Error: " << e.what();
  274. throw; //obviously we cannot continue here
  275. }
  276. /*
  277. if(!server)
  278. player = PlayerColor(player_);
  279. */
  280. std::set<PlayerColor> clientPlayers;
  281. if(server)
  282. serv = sh.connectToServer();
  283. //*loader >> *this;
  284. if(server)
  285. {
  286. tmh.update();
  287. ui8 pom8;
  288. *serv << ui8(3) << ui8(loadNumPlayers); //load game; one client if single-player
  289. *serv << fname;
  290. *serv >> pom8;
  291. if(pom8)
  292. throw std::runtime_error("Server cannot open the savegame!");
  293. else
  294. logNetwork->infoStream() << "Server opened savegame properly.";
  295. }
  296. if(server)
  297. {
  298. for(auto & elem : gs->scenarioOps->playerInfos)
  299. {
  300. if(!std::count(humanplayerindices.begin(),humanplayerindices.end(),elem.first.getNum()) || elem.first==player)
  301. clientPlayers.insert(elem.first);
  302. }
  303. clientPlayers.insert(PlayerColor::NEUTRAL);
  304. }
  305. else
  306. {
  307. clientPlayers.insert(player);
  308. }
  309. std::cout << "CLIENTPLAYERS:\n";
  310. for(auto x : clientPlayers)
  311. std::cout << x << std::endl;
  312. std::cout << "ENDCLIENTPLAYERS\n";
  313. serialize(loader->serializer,0,clientPlayers);
  314. *serv << ui32(clientPlayers.size());
  315. for(auto & elem : clientPlayers)
  316. *serv << ui8(elem.getNum());
  317. serv->addStdVecItems(gs); /*why is this here?*/
  318. //*loader >> *this;
  319. logNetwork->infoStream() << "Loaded client part of save " << tmh.getDiff();
  320. logNetwork->infoStream() <<"Sent info to server: "<<tmh.getDiff();
  321. //*serv << clientPlayers;
  322. serv->enableStackSendingByID();
  323. serv->disableSmartPointerSerialization();
  324. // logGlobal->traceStream() << "Objects:";
  325. // for(int i = 0; i < gs->map->objects.size(); i++)
  326. // {
  327. // auto o = gs->map->objects[i];
  328. // if(o)
  329. // logGlobal->traceStream() << boost::format("\tindex=%5d, id=%5d; address=%5d, pos=%s, name=%s") % i % o->id % (int)o.get() % o->pos % o->getHoverText();
  330. // else
  331. // logGlobal->traceStream() << boost::format("\tindex=%5d --- nullptr") % i;
  332. // }
  333. }
  334. #endif
  335. void CClient::newGame( CConnection *con, StartInfo *si )
  336. {
  337. enum {SINGLE, HOST, GUEST} networkMode = SINGLE;
  338. if (con == nullptr)
  339. {
  340. CServerHandler sh;
  341. serv = sh.connectToServer();
  342. }
  343. else
  344. {
  345. serv = con;
  346. networkMode = (con->connectionID == 1) ? HOST : GUEST;
  347. }
  348. CConnection &c = *serv;
  349. ////////////////////////////////////////////////////
  350. logNetwork->infoStream() <<"\tWill send info to server...";
  351. CStopWatch tmh;
  352. if(networkMode == SINGLE)
  353. {
  354. ui8 pom8;
  355. c << ui8(2) << ui8(1); //new game; one client
  356. c << *si;
  357. c >> pom8;
  358. if(pom8) throw std::runtime_error("Server cannot open the map!");
  359. }
  360. c >> si;
  361. logNetwork->infoStream() <<"\tSending/Getting info to/from the server: "<<tmh.getDiff();
  362. c.enableStackSendingByID();
  363. c.disableSmartPointerSerialization();
  364. // Initialize game state
  365. gs = new CGameState();
  366. logNetwork->infoStream() <<"\tCreating gamestate: "<<tmh.getDiff();
  367. gs->scenarioOps = si;
  368. gs->init(si);
  369. logNetwork->infoStream() <<"Initializing GameState (together): "<<tmh.getDiff();
  370. // Now after possible random map gen, we know exact player count.
  371. // Inform server about how many players client handles
  372. std::set<PlayerColor> myPlayers;
  373. for(auto & elem : gs->scenarioOps->playerInfos)
  374. {
  375. if((networkMode == SINGLE) //single - one client has all player
  376. || (networkMode != SINGLE && serv->connectionID == elem.second.playerID) //multi - client has only "its players"
  377. || (networkMode == HOST && elem.second.playerID == PlayerSettings::PLAYER_AI))//multi - host has all AI players
  378. {
  379. myPlayers.insert(elem.first); //add player
  380. }
  381. }
  382. if(networkMode != GUEST)
  383. myPlayers.insert(PlayerColor::NEUTRAL);
  384. c << myPlayers;
  385. // Init map handler
  386. if(gs->map)
  387. {
  388. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  389. CGI->mh->map = gs->map;
  390. logNetwork->infoStream() << "Creating mapHandler: " << tmh.getDiff();
  391. CGI->mh->init();
  392. pathInfo = make_unique<CPathsInfo>(getMapSize());
  393. logNetwork->infoStream() << "Initializing mapHandler (together): " << tmh.getDiff();
  394. }
  395. int humanPlayers = 0;
  396. for(auto & elem : gs->scenarioOps->playerInfos)//initializing interfaces for players
  397. {
  398. PlayerColor color = elem.first;
  399. gs->currentPlayer = color;
  400. if(!vstd::contains(myPlayers, color))
  401. continue;
  402. logNetwork->traceStream() << "Preparing interface for player " << color;
  403. if(si->mode != StartInfo::DUEL)
  404. {
  405. if(elem.second.playerID == PlayerSettings::PLAYER_AI)
  406. {
  407. auto AiToGive = aiNameForPlayer(elem.second, false);
  408. logNetwork->infoStream() << boost::format("Player %s will be lead by %s") % color % AiToGive;
  409. installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color);
  410. }
  411. else
  412. {
  413. installNewPlayerInterface(std::make_shared<CPlayerInterface>(color), color);
  414. humanPlayers++;
  415. }
  416. }
  417. else
  418. {
  419. std::string AItoGive = aiNameForPlayer(elem.second, true);
  420. installNewBattleInterface(CDynLibHandler::getNewBattleAI(AItoGive), color);
  421. }
  422. }
  423. if(si->mode == StartInfo::DUEL)
  424. {
  425. if(!gNoGUI)
  426. {
  427. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  428. auto p = std::make_shared<CPlayerInterface>(PlayerColor::NEUTRAL);
  429. p->observerInDuelMode = true;
  430. installNewPlayerInterface(p, boost::none);
  431. GH.curInt = p.get();
  432. }
  433. battleStarted(gs->curB);
  434. }
  435. else
  436. {
  437. loadNeutralBattleAI();
  438. }
  439. serv->addStdVecItems(gs);
  440. hotSeat = (humanPlayers > 1);
  441. // std::vector<FileInfo> scriptModules;
  442. // CFileUtility::getFilesWithExt(scriptModules, LIB_DIR "/scripting", "." LIB_EXT);
  443. // for(FileInfo &m : scriptModules)
  444. // {
  445. // CScriptingModule * nm = CDynLibHandler::getNewScriptingModule(m.name);
  446. // privilagedGameEventReceivers.push_back(nm);
  447. // privilagedBattleEventReceivers.push_back(nm);
  448. // nm->giveActionCB(this);
  449. // nm->giveInfoCB(this);
  450. // nm->init();
  451. //
  452. // erm = nm; //something tells me that there'll at most one module and it'll be ERM
  453. // }
  454. }
  455. void CClient::serialize(BinarySerializer & h, const int version)
  456. {
  457. assert(h.saving);
  458. h & hotSeat;
  459. {
  460. ui8 players = playerint.size();
  461. h & players;
  462. for(auto i = playerint.begin(); i != playerint.end(); i++)
  463. {
  464. LOG_TRACE_PARAMS(logGlobal, "Saving player %s interface", i->first);
  465. assert(i->first == i->second->playerID);
  466. h & i->first & i->second->dllName & i->second->human;
  467. i->second->saveGame(h, version);
  468. }
  469. }
  470. }
  471. void CClient::serialize(BinaryDeserializer & h, const int version)
  472. {
  473. assert(!h.saving);
  474. h & hotSeat;
  475. {
  476. ui8 players = 0; //fix for uninitialized warning
  477. h & players;
  478. for(int i=0; i < players; i++)
  479. {
  480. std::string dllname;
  481. PlayerColor pid;
  482. bool isHuman = false;
  483. h & pid & dllname & isHuman;
  484. LOG_TRACE_PARAMS(logGlobal, "Loading player %s interface", pid);
  485. std::shared_ptr<CGameInterface> nInt;
  486. if(dllname.length())
  487. {
  488. if(pid == PlayerColor::NEUTRAL)
  489. {
  490. installNewBattleInterface(CDynLibHandler::getNewBattleAI(dllname), pid);
  491. //TODO? consider serialization
  492. continue;
  493. }
  494. else
  495. {
  496. assert(!isHuman);
  497. nInt = CDynLibHandler::getNewAI(dllname);
  498. }
  499. }
  500. else
  501. {
  502. assert(isHuman);
  503. nInt = std::make_shared<CPlayerInterface>(pid);
  504. }
  505. nInt->dllName = dllname;
  506. nInt->human = isHuman;
  507. nInt->playerID = pid;
  508. installNewPlayerInterface(nInt, pid);
  509. nInt->loadGame(h, version); //another evil cast, check above
  510. }
  511. if(!vstd::contains(battleints, PlayerColor::NEUTRAL))
  512. loadNeutralBattleAI();
  513. }
  514. }
  515. void CClient::serialize(BinarySerializer & h, const int version, const std::set<PlayerColor> & playerIDs)
  516. {
  517. assert(h.saving);
  518. h & hotSeat;
  519. {
  520. ui8 players = playerint.size();
  521. h & players;
  522. for(auto i = playerint.begin(); i != playerint.end(); i++)
  523. {
  524. LOG_TRACE_PARAMS(logGlobal, "Saving player %s interface", i->first);
  525. assert(i->first == i->second->playerID);
  526. h & i->first & i->second->dllName & i->second->human;
  527. i->second->saveGame(h, version);
  528. }
  529. }
  530. }
  531. void CClient::serialize(BinaryDeserializer & h, const int version, const std::set<PlayerColor> & playerIDs)
  532. {
  533. assert(!h.saving);
  534. h & hotSeat;
  535. {
  536. ui8 players = 0; //fix for uninitialized warning
  537. h & players;
  538. for(int i=0; i < players; i++)
  539. {
  540. std::string dllname;
  541. PlayerColor pid;
  542. bool isHuman = false;
  543. h & pid & dllname & isHuman;
  544. LOG_TRACE_PARAMS(logGlobal, "Loading player %s interface", pid);
  545. std::shared_ptr<CGameInterface> nInt;
  546. if(dllname.length())
  547. {
  548. if(pid == PlayerColor::NEUTRAL)
  549. {
  550. if(playerIDs.count(pid))
  551. installNewBattleInterface(CDynLibHandler::getNewBattleAI(dllname), pid);
  552. //TODO? consider serialization
  553. continue;
  554. }
  555. else
  556. {
  557. assert(!isHuman);
  558. nInt = CDynLibHandler::getNewAI(dllname);
  559. }
  560. }
  561. else
  562. {
  563. assert(isHuman);
  564. nInt = std::make_shared<CPlayerInterface>(pid);
  565. }
  566. nInt->dllName = dllname;
  567. nInt->human = isHuman;
  568. nInt->playerID = pid;
  569. if(playerIDs.count(pid))
  570. installNewPlayerInterface(nInt, pid);
  571. nInt->loadGame(h, version);
  572. }
  573. if(playerIDs.count(PlayerColor::NEUTRAL))
  574. loadNeutralBattleAI();
  575. }
  576. }
  577. void CClient::handlePack( CPack * pack )
  578. {
  579. if(pack == nullptr)
  580. {
  581. logNetwork->error("Dropping nullptr CPack! You should check whether client and server ABI matches.");
  582. return;
  583. }
  584. CBaseForCLApply *apply = applier->getApplier(typeList.getTypeID(pack)); //find the applier
  585. if(apply)
  586. {
  587. boost::unique_lock<boost::recursive_mutex> guiLock(*LOCPLINT->pim);
  588. apply->applyOnClBefore(this, pack);
  589. logNetwork->trace("\tMade first apply on cl");
  590. gs->apply(pack);
  591. logNetwork->trace("\tApplied on gs");
  592. apply->applyOnClAfter(this, pack);
  593. logNetwork->trace("\tMade second apply on cl");
  594. }
  595. else
  596. {
  597. logNetwork->error("Message cannot be applied, cannot find applier! type %d - %s",
  598. pack->type, typeList.getTypeInfo(pack)->name());
  599. }
  600. delete pack;
  601. }
  602. void CClient::finishCampaign( std::shared_ptr<CCampaignState> camp )
  603. {
  604. }
  605. void CClient::proposeNextMission(std::shared_ptr<CCampaignState> camp)
  606. {
  607. GH.pushInt(new CBonusSelection(camp));
  608. }
  609. void CClient::stopConnection()
  610. {
  611. terminate = true;
  612. if (serv) //request closing connection
  613. {
  614. logNetwork->infoStream() << "Connection has been requested to be closed.";
  615. boost::unique_lock<boost::mutex>(*serv->wmx);
  616. CloseServer close_server;
  617. sendRequest(&close_server, PlayerColor::NEUTRAL);
  618. logNetwork->infoStream() << "Sent closing signal to the server";
  619. }
  620. if(connectionHandler)//end connection handler
  621. {
  622. if(connectionHandler->get_id() != boost::this_thread::get_id())
  623. connectionHandler->join();
  624. logNetwork->infoStream() << "Connection handler thread joined";
  625. delete connectionHandler;
  626. connectionHandler = nullptr;
  627. }
  628. if (serv) //and delete connection
  629. {
  630. serv->close();
  631. delete serv;
  632. serv = nullptr;
  633. logNetwork->warnStream() << "Our socket has been closed.";
  634. }
  635. }
  636. void CClient::battleStarted(const BattleInfo * info)
  637. {
  638. for(auto &battleCb : battleCallbacks)
  639. {
  640. if(vstd::contains_if(info->sides, [&](const SideInBattle& side) {return side.color == battleCb.first; })
  641. || battleCb.first >= PlayerColor::PLAYER_LIMIT)
  642. {
  643. battleCb.second->setBattle(info);
  644. }
  645. }
  646. // for(ui8 side : info->sides)
  647. // if(battleCallbacks.count(side))
  648. // battleCallbacks[side]->setBattle(info);
  649. std::shared_ptr<CPlayerInterface> att, def;
  650. auto &leftSide = info->sides[0], &rightSide = info->sides[1];
  651. //If quick combat is not, do not prepare interfaces for battleint
  652. if(!settings["adventure"]["quickCombat"].Bool())
  653. {
  654. if(vstd::contains(playerint, leftSide.color) && playerint[leftSide.color]->human)
  655. att = std::dynamic_pointer_cast<CPlayerInterface>( playerint[leftSide.color] );
  656. if(vstd::contains(playerint, rightSide.color) && playerint[rightSide.color]->human)
  657. def = std::dynamic_pointer_cast<CPlayerInterface>( playerint[rightSide.color] );
  658. }
  659. if(!gNoGUI && (!!att || !!def || gs->scenarioOps->mode == StartInfo::DUEL))
  660. {
  661. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  662. auto bi = new CBattleInterface(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero,
  663. Rect((screen->w - 800)/2,
  664. (screen->h - 600)/2, 800, 600), att, def);
  665. GH.pushInt(bi);
  666. }
  667. auto callBattleStart = [&](PlayerColor color, ui8 side){
  668. if(vstd::contains(battleints, color))
  669. battleints[color]->battleStart(leftSide.armyObject, rightSide.armyObject, info->tile, leftSide.hero, rightSide.hero, side);
  670. };
  671. callBattleStart(leftSide.color, 0);
  672. callBattleStart(rightSide.color, 1);
  673. callBattleStart(PlayerColor::UNFLAGGABLE, 1);
  674. if(info->tacticDistance && vstd::contains(battleints,info->sides[info->tacticsSide].color))
  675. {
  676. boost::thread(&CClient::commenceTacticPhaseForInt, this, battleints[info->sides[info->tacticsSide].color]);
  677. }
  678. }
  679. void CClient::battleFinished()
  680. {
  681. for(auto & side : gs->curB->sides)
  682. if(battleCallbacks.count(side.color))
  683. battleCallbacks[side.color]->setBattle(nullptr);
  684. }
  685. void CClient::loadNeutralBattleAI()
  686. {
  687. installNewBattleInterface(CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String()), PlayerColor::NEUTRAL);
  688. }
  689. void CClient::commitPackage( CPackForClient *pack )
  690. {
  691. CommitPackage cp;
  692. cp.freePack = false;
  693. cp.packToCommit = pack;
  694. sendRequest(&cp, PlayerColor::NEUTRAL);
  695. }
  696. PlayerColor CClient::getLocalPlayer() const
  697. {
  698. if(LOCPLINT)
  699. return LOCPLINT->playerID;
  700. return getCurrentPlayer();
  701. }
  702. void CClient::commenceTacticPhaseForInt(std::shared_ptr<CBattleGameInterface> battleInt)
  703. {
  704. setThreadName("CClient::commenceTacticPhaseForInt");
  705. try
  706. {
  707. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  708. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  709. {
  710. MakeAction ma(BattleAction::makeEndOFTacticPhase(gs->curB->playerToSide(battleInt->playerID)));
  711. sendRequest(&ma, battleInt->playerID);
  712. }
  713. }
  714. catch(...)
  715. {
  716. handleException();
  717. }
  718. }
  719. void CClient::invalidatePaths()
  720. {
  721. // turn pathfinding info into invalid. It will be regenerated later
  722. boost::unique_lock<boost::mutex> pathLock(pathInfo->pathMx);
  723. pathInfo->hero = nullptr;
  724. }
  725. const CPathsInfo * CClient::getPathsInfo(const CGHeroInstance *h)
  726. {
  727. assert(h);
  728. boost::unique_lock<boost::mutex> pathLock(pathInfo->pathMx);
  729. if (pathInfo->hero != h)
  730. {
  731. gs->calculatePaths(h, *pathInfo.get());
  732. }
  733. return pathInfo.get();
  734. }
  735. int CClient::sendRequest(const CPack *request, PlayerColor player)
  736. {
  737. static ui32 requestCounter = 0;
  738. ui32 requestID = requestCounter++;
  739. logNetwork->traceStream() << boost::format("Sending a request \"%s\". It'll have an ID=%d.")
  740. % typeid(*request).name() % requestID;
  741. waitingRequest.pushBack(requestID);
  742. serv->sendPackToServer(*request, player, requestID);
  743. if(vstd::contains(playerint, player))
  744. playerint[player]->requestSent(dynamic_cast<const CPackForServer*>(request), requestID);
  745. return requestID;
  746. }
  747. void CClient::campaignMapFinished( std::shared_ptr<CCampaignState> camp )
  748. {
  749. endGame(false);
  750. GH.curInt = CGPreGame::create();
  751. auto & epilogue = camp->camp->scenarios[camp->mapsConquered.back()].epilog;
  752. auto finisher = [=]()
  753. {
  754. if(camp->mapsRemaining.size())
  755. proposeNextMission(camp);
  756. else
  757. finishCampaign(camp);
  758. };
  759. if(epilogue.hasPrologEpilog)
  760. {
  761. GH.pushInt(new CPrologEpilogVideo(epilogue, finisher));
  762. }
  763. else
  764. {
  765. finisher();
  766. }
  767. }
  768. void CClient::installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, boost::optional<PlayerColor> color)
  769. {
  770. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  771. PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);
  772. if(!color)
  773. privilagedGameEventReceivers.push_back(gameInterface);
  774. playerint[colorUsed] = gameInterface;
  775. logGlobal->traceStream() << boost::format("\tInitializing the interface for player %s") % colorUsed;
  776. auto cb = std::make_shared<CCallback>(gs, color, this);
  777. callbacks[colorUsed] = cb;
  778. battleCallbacks[colorUsed] = cb;
  779. gameInterface->init(cb);
  780. installNewBattleInterface(gameInterface, color, false);
  781. }
  782. void CClient::installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, boost::optional<PlayerColor> color, bool needCallback /*= true*/)
  783. {
  784. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  785. PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);
  786. if(!color)
  787. privilagedBattleEventReceivers.push_back(battleInterface);
  788. battleints[colorUsed] = battleInterface;
  789. if(needCallback)
  790. {
  791. logGlobal->traceStream() << boost::format("\tInitializing the battle interface for player %s") % *color;
  792. auto cbc = std::make_shared<CBattleCallback>(gs, color, this);
  793. battleCallbacks[colorUsed] = cbc;
  794. battleInterface->init(cbc);
  795. }
  796. }
  797. std::string CClient::aiNameForPlayer(const PlayerSettings &ps, bool battleAI)
  798. {
  799. if(ps.name.size())
  800. {
  801. const boost::filesystem::path aiPath =
  802. VCMIDirs::get().libraryPath() / "AI" / VCMIDirs::get().libraryName(ps.name);
  803. if (boost::filesystem::exists(aiPath))
  804. return ps.name;
  805. }
  806. const int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
  807. std::string goodAI = battleAI ? settings["server"]["neutralAI"].String() : settings["server"]["playerAI"].String();
  808. std::string badAI = battleAI ? "StupidAI" : "EmptyAI";
  809. //TODO what about human players
  810. if(battleints.size() >= sensibleAILimit)
  811. return badAI;
  812. return goodAI;
  813. }
  814. bool CServerHandler::DO_NOT_START_SERVER = false;
  815. void CServerHandler::startServer()
  816. {
  817. if(DO_NOT_START_SERVER)
  818. return;
  819. th.update();
  820. serverThread = new boost::thread(&CServerHandler::callServer, this); //runs server executable;
  821. if(verbose)
  822. logNetwork->infoStream() << "Setting up thread calling server: " << th.getDiff();
  823. }
  824. void CServerHandler::waitForServer()
  825. {
  826. if(DO_NOT_START_SERVER)
  827. return;
  828. if(!serverThread)
  829. startServer();
  830. th.update();
  831. #ifndef VCMI_ANDROID
  832. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  833. while(!shared->sr->ready)
  834. {
  835. shared->sr->cond.wait(slock);
  836. }
  837. #endif
  838. if(verbose)
  839. logNetwork->infoStream() << "Waiting for server: " << th.getDiff();
  840. }
  841. CConnection * CServerHandler::connectToServer()
  842. {
  843. #ifndef VCMI_ANDROID
  844. if(!shared->sr->ready)
  845. waitForServer();
  846. #else
  847. waitForServer();
  848. #endif
  849. th.update(); //put breakpoint here to attach to server before it does something stupid
  850. CConnection *ret = justConnectToServer(settings["server"]["server"].String(), port);
  851. if(verbose)
  852. logNetwork->infoStream()<<"\tConnecting to the server: "<<th.getDiff();
  853. return ret;
  854. }
  855. CServerHandler::CServerHandler(bool runServer /*= false*/)
  856. {
  857. serverThread = nullptr;
  858. shared = nullptr;
  859. if(settings["testing"]["enabled"].Bool())
  860. port = settings["testing"]["port"].String();
  861. else
  862. port = boost::lexical_cast<std::string>(settings["server"]["port"].Float());
  863. verbose = true;
  864. #ifndef VCMI_ANDROID
  865. boost::interprocess::shared_memory_object::remove("vcmi_memory"); //if the application has previously crashed, the memory may not have been removed. to avoid problems - try to destroy it
  866. try
  867. {
  868. shared = new SharedMem();
  869. }
  870. catch(...)
  871. {
  872. logNetwork->error("Cannot open interprocess memory.");
  873. handleException();
  874. throw;
  875. }
  876. #endif
  877. }
  878. CServerHandler::~CServerHandler()
  879. {
  880. delete shared;
  881. delete serverThread; //detaches, not kills thread
  882. }
  883. void CServerHandler::callServer()
  884. {
  885. setThreadName("CServerHandler::callServer");
  886. const std::string logName = (VCMIDirs::get().userCachePath() / "server_log.txt").string();
  887. const std::string comm = VCMIDirs::get().serverPath().string() + " --port=" + port + " > \"" + logName + '\"';
  888. int result = std::system(comm.c_str());
  889. if (result == 0)
  890. logNetwork->infoStream() << "Server closed correctly";
  891. else
  892. {
  893. logNetwork->errorStream() << "Error: server failed to close correctly or crashed!";
  894. logNetwork->errorStream() << "Check " << logName << " for more info";
  895. exit(1);// exit in case of error. Othervice without working server VCMI will hang
  896. }
  897. }
  898. CConnection * CServerHandler::justConnectToServer(const std::string &host, const std::string &port)
  899. {
  900. std::string realPort;
  901. if(settings["testing"]["enabled"].Bool())
  902. realPort = settings["testing"]["port"].String();
  903. else if(port.size())
  904. realPort = port;
  905. else
  906. realPort = boost::lexical_cast<std::string>(settings["server"]["port"].Float());
  907. CConnection *ret = nullptr;
  908. while(!ret)
  909. {
  910. try
  911. {
  912. logNetwork->infoStream() << "Establishing connection...";
  913. ret = new CConnection( host.size() ? host : settings["server"]["server"].String(),
  914. realPort,
  915. NAME);
  916. }
  917. catch(...)
  918. {
  919. logNetwork->errorStream() << "\nCannot establish connection! Retrying within 2 seconds";
  920. SDL_Delay(2000);
  921. }
  922. }
  923. return ret;
  924. }