2
0

Client.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  1. /*
  2. * Client.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 "Client.h"
  12. #include <SDL.h>
  13. #include "CMusicHandler.h"
  14. #include "../lib/mapping/CCampaignHandler.h"
  15. #include "../CCallback.h"
  16. #include "../lib/CConsoleHandler.h"
  17. #include "CGameInfo.h"
  18. #include "../lib/CGameState.h"
  19. #include "CPlayerInterface.h"
  20. #include "../lib/StartInfo.h"
  21. #include "../lib/battle/BattleInfo.h"
  22. #include "../lib/CModHandler.h"
  23. #include "../lib/CArtHandler.h"
  24. #include "../lib/CGeneralTextHandler.h"
  25. #include "../lib/CHeroHandler.h"
  26. #include "../lib/CTownHandler.h"
  27. #include "../lib/CBuildingHandler.h"
  28. #include "../lib/spells/CSpellHandler.h"
  29. #include "../lib/serializer/CTypeList.h"
  30. #include "../lib/serializer/Connection.h"
  31. #include "../lib/serializer/CLoadIntegrityValidator.h"
  32. #include "../lib/NetPacks.h"
  33. #include "../lib/VCMI_Lib.h"
  34. #include "../lib/VCMIDirs.h"
  35. #include "../lib/mapping/CMap.h"
  36. #include "../lib/mapping/CMapService.h"
  37. #include "../lib/JsonNode.h"
  38. #include "mapHandler.h"
  39. #include "../lib/CConfigHandler.h"
  40. #include "mainmenu/CMainMenu.h"
  41. #include "mainmenu/CCampaignScreen.h"
  42. #include "lobby/CBonusSelection.h"
  43. #include "battle/BattleInterface.h"
  44. #include "../lib/CThreadHelper.h"
  45. #include "../lib/registerTypes/RegisterTypes.h"
  46. #include "gui/CGuiHandler.h"
  47. #include "CServerHandler.h"
  48. #include "../lib/ScriptHandler.h"
  49. #include "windows/CAdvmapInterface.h"
  50. #include <vcmi/events/EventBus.h>
  51. #ifdef VCMI_ANDROID
  52. #include "lib/CAndroidVMHelper.h"
  53. #endif
  54. #ifdef VCMI_ANDROID
  55. std::atomic_bool androidTestServerReadyFlag;
  56. #endif
  57. ThreadSafeVector<int> CClient::waitingRequest;
  58. template<typename T> class CApplyOnCL;
  59. class CBaseForCLApply
  60. {
  61. public:
  62. virtual void applyOnClAfter(CClient * cl, void * pack) const =0;
  63. virtual void applyOnClBefore(CClient * cl, void * pack) const =0;
  64. virtual ~CBaseForCLApply(){}
  65. template<typename U> static CBaseForCLApply * getApplier(const U * t = nullptr)
  66. {
  67. return new CApplyOnCL<U>();
  68. }
  69. };
  70. template<typename T> class CApplyOnCL : public CBaseForCLApply
  71. {
  72. public:
  73. void applyOnClAfter(CClient * cl, void * pack) const override
  74. {
  75. T * ptr = static_cast<T *>(pack);
  76. ptr->applyCl(cl);
  77. }
  78. void applyOnClBefore(CClient * cl, void * pack) const override
  79. {
  80. T * ptr = static_cast<T *>(pack);
  81. ptr->applyFirstCl(cl);
  82. }
  83. };
  84. template<> class CApplyOnCL<CPack>: public CBaseForCLApply
  85. {
  86. public:
  87. void applyOnClAfter(CClient * cl, void * pack) const override
  88. {
  89. logGlobal->error("Cannot apply on CL plain CPack!");
  90. assert(0);
  91. }
  92. void applyOnClBefore(CClient * cl, void * pack) const override
  93. {
  94. logGlobal->error("Cannot apply on CL plain CPack!");
  95. assert(0);
  96. }
  97. };
  98. CPlayerEnvironment::CPlayerEnvironment(PlayerColor player_, CClient * cl_, std::shared_ptr<CCallback> mainCallback_)
  99. : player(player_),
  100. cl(cl_),
  101. mainCallback(mainCallback_)
  102. {
  103. }
  104. const Services * CPlayerEnvironment::services() const
  105. {
  106. return VLC;
  107. }
  108. vstd::CLoggerBase * CPlayerEnvironment::logger() const
  109. {
  110. return logGlobal;
  111. }
  112. events::EventBus * CPlayerEnvironment::eventBus() const
  113. {
  114. return cl->eventBus();//always get actual value
  115. }
  116. const CPlayerEnvironment::BattleCb * CPlayerEnvironment::battle() const
  117. {
  118. return mainCallback.get();
  119. }
  120. const CPlayerEnvironment::GameCb * CPlayerEnvironment::game() const
  121. {
  122. return mainCallback.get();
  123. }
  124. CClient::CClient()
  125. {
  126. waitingRequest.clear();
  127. applier = std::make_shared<CApplier<CBaseForCLApply>>();
  128. registerTypesClientPacks1(*applier);
  129. registerTypesClientPacks2(*applier);
  130. IObjectInterface::cb = this;
  131. gs = nullptr;
  132. }
  133. CClient::~CClient()
  134. {
  135. IObjectInterface::cb = nullptr;
  136. }
  137. const Services * CClient::services() const
  138. {
  139. return VLC; //todo: this should be CGI
  140. }
  141. const CClient::BattleCb * CClient::battle() const
  142. {
  143. return this;
  144. }
  145. const CClient::GameCb * CClient::game() const
  146. {
  147. return this;
  148. }
  149. vstd::CLoggerBase * CClient::logger() const
  150. {
  151. return logGlobal;
  152. }
  153. events::EventBus * CClient::eventBus() const
  154. {
  155. return clientEventBus.get();
  156. }
  157. void CClient::newGame(CGameState * initializedGameState)
  158. {
  159. CSH->th->update();
  160. CMapService mapService;
  161. gs = initializedGameState ? initializedGameState : new CGameState();
  162. gs->preInit(VLC);
  163. logNetwork->trace("\tCreating gamestate: %i", CSH->th->getDiff());
  164. if(!initializedGameState)
  165. gs->init(&mapService, CSH->si.get(), settings["general"]["saveRandomMaps"].Bool());
  166. logNetwork->trace("Initializing GameState (together): %d ms", CSH->th->getDiff());
  167. initMapHandler();
  168. reinitScripting();
  169. initPlayerEnvironments();
  170. initPlayerInterfaces();
  171. }
  172. void CClient::loadGame(CGameState * initializedGameState)
  173. {
  174. logNetwork->info("Loading procedure started!");
  175. std::unique_ptr<CLoadFile> loader;
  176. if(initializedGameState)
  177. {
  178. logNetwork->info("Game state was transferred over network, loading.");
  179. gs = initializedGameState;
  180. }
  181. else
  182. {
  183. try
  184. {
  185. boost::filesystem::path clientSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(CSH->si->mapname, EResType::CLIENT_SAVEGAME));
  186. boost::filesystem::path controlServerSaveName;
  187. if(CResourceHandler::get("local")->existsResource(ResourceID(CSH->si->mapname, EResType::SERVER_SAVEGAME)))
  188. {
  189. controlServerSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(CSH->si->mapname, EResType::SERVER_SAVEGAME));
  190. }
  191. else // create entry for server savegame. Triggered if save was made after launch and not yet present in res handler
  192. {
  193. controlServerSaveName = boost::filesystem::path(clientSaveName).replace_extension(".vsgm1");
  194. CResourceHandler::get("local")->createResource(controlServerSaveName.string(), true);
  195. }
  196. if(clientSaveName.empty())
  197. throw std::runtime_error("Cannot open client part of " + CSH->si->mapname);
  198. if(controlServerSaveName.empty() || !boost::filesystem::exists(controlServerSaveName))
  199. throw std::runtime_error("Cannot open server part of " + CSH->si->mapname);
  200. {
  201. CLoadIntegrityValidator checkingLoader(clientSaveName, controlServerSaveName, MINIMAL_SERIALIZATION_VERSION);
  202. loadCommonState(checkingLoader);
  203. loader = checkingLoader.decay();
  204. }
  205. }
  206. catch(std::exception & e)
  207. {
  208. logGlobal->error("Cannot load game %s. Error: %s", CSH->si->mapname, e.what());
  209. throw; //obviously we cannot continue here
  210. }
  211. logNetwork->trace("Loaded common part of save %d ms", CSH->th->getDiff());
  212. }
  213. gs->preInit(VLC);
  214. gs->updateOnLoad(CSH->si.get());
  215. logNetwork->info("Game loaded, initialize interfaces.");
  216. initMapHandler();
  217. reinitScripting();
  218. initPlayerEnvironments();
  219. if(loader)
  220. serialize(loader->serializer, loader->serializer.fileVersion);
  221. initPlayerInterfaces();
  222. }
  223. void CClient::serialize(BinarySerializer & h, const int version)
  224. {
  225. assert(h.saving);
  226. ui8 players = static_cast<ui8>(playerint.size());
  227. h & players;
  228. for(auto i = playerint.begin(); i != playerint.end(); i++)
  229. {
  230. logGlobal->trace("Saving player %s interface", i->first);
  231. assert(i->first == i->second->playerID);
  232. h & i->first;
  233. h & i->second->dllName;
  234. h & i->second->human;
  235. i->second->saveGame(h, version);
  236. }
  237. #if SCRIPTING_ENABLED
  238. if(version >= 800)
  239. {
  240. JsonNode scriptsState;
  241. clientScripts->serializeState(h.saving, scriptsState);
  242. h & scriptsState;
  243. }
  244. #endif
  245. }
  246. void CClient::serialize(BinaryDeserializer & h, const int version)
  247. {
  248. assert(!h.saving);
  249. ui8 players = 0;
  250. h & players;
  251. for(int i = 0; i < players; i++)
  252. {
  253. std::string dllname;
  254. PlayerColor pid;
  255. bool isHuman = false;
  256. auto prevInt = LOCPLINT;
  257. h & pid;
  258. h & dllname;
  259. h & isHuman;
  260. assert(dllname.length() == 0 || !isHuman);
  261. if(pid == PlayerColor::NEUTRAL)
  262. {
  263. logGlobal->trace("Neutral battle interfaces are not serialized.");
  264. continue;
  265. }
  266. logGlobal->trace("Loading player %s interface", pid);
  267. std::shared_ptr<CGameInterface> nInt;
  268. if(dllname.length())
  269. nInt = CDynLibHandler::getNewAI(dllname);
  270. else
  271. nInt = std::make_shared<CPlayerInterface>(pid);
  272. nInt->dllName = dllname;
  273. nInt->human = isHuman;
  274. nInt->playerID = pid;
  275. nInt->loadGame(h, version);
  276. // Client no longer handle this player at all
  277. if(!vstd::contains(CSH->getAllClientPlayers(CSH->c->connectionID), pid))
  278. {
  279. logGlobal->trace("Player %s is not belong to this client. Destroying interface", pid);
  280. }
  281. else if(isHuman && !vstd::contains(CSH->getHumanColors(), pid))
  282. {
  283. logGlobal->trace("Player %s is no longer controlled by human. Destroying interface", pid);
  284. }
  285. else if(!isHuman && vstd::contains(CSH->getHumanColors(), pid))
  286. {
  287. logGlobal->trace("Player %s is no longer controlled by AI. Destroying interface", pid);
  288. }
  289. else
  290. {
  291. installNewPlayerInterface(nInt, pid);
  292. continue;
  293. }
  294. nInt.reset();
  295. LOCPLINT = prevInt;
  296. }
  297. #if SCRIPTING_ENABLED
  298. {
  299. JsonNode scriptsState;
  300. h & scriptsState;
  301. clientScripts->serializeState(h.saving, scriptsState);
  302. }
  303. #endif
  304. logNetwork->trace("Loaded client part of save %d ms", CSH->th->getDiff());
  305. }
  306. void CClient::save(const std::string & fname)
  307. {
  308. if(gs->curB)
  309. {
  310. logNetwork->error("Game cannot be saved during battle!");
  311. return;
  312. }
  313. SaveGame save_game(fname);
  314. sendRequest(&save_game, PlayerColor::NEUTRAL);
  315. }
  316. void CClient::endGame()
  317. {
  318. #if SCRIPTING_ENABLED
  319. clientScripts.reset();
  320. #endif
  321. //suggest interfaces to finish their stuff (AI should interrupt any bg working threads)
  322. for(auto & i : playerint)
  323. i.second->finish();
  324. GH.curInt = nullptr;
  325. {
  326. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  327. logNetwork->info("Ending current game!");
  328. removeGUI();
  329. vstd::clear_pointer(const_cast<CGameInfo *>(CGI)->mh);
  330. vstd::clear_pointer(gs);
  331. logNetwork->info("Deleted mapHandler and gameState.");
  332. }
  333. playerint.clear();
  334. battleints.clear();
  335. battleCallbacks.clear();
  336. playerEnvironments.clear();
  337. logNetwork->info("Deleted playerInts.");
  338. logNetwork->info("Client stopped.");
  339. }
  340. void CClient::initMapHandler()
  341. {
  342. // TODO: CMapHandler initialization can probably go somewhere else
  343. // It's can't be before initialization of interfaces
  344. // During loading CPlayerInterface from serialized state it's depend on MH
  345. if(!settings["session"]["headless"].Bool())
  346. {
  347. const_cast<CGameInfo *>(CGI)->mh = new CMapHandler();
  348. CGI->mh->map = gs->map;
  349. logNetwork->trace("Creating mapHandler: %d ms", CSH->th->getDiff());
  350. CGI->mh->init();
  351. logNetwork->trace("Initializing mapHandler (together): %d ms", CSH->th->getDiff());
  352. }
  353. pathCache.clear();
  354. }
  355. void CClient::initPlayerEnvironments()
  356. {
  357. playerEnvironments.clear();
  358. auto allPlayers = CSH->getAllClientPlayers(CSH->c->connectionID);
  359. for(auto & color : allPlayers)
  360. {
  361. logNetwork->info("Preparing environment for player %s", color.getStr());
  362. playerEnvironments[color] = std::make_shared<CPlayerEnvironment>(color, this, std::make_shared<CCallback>(gs, color, this));
  363. }
  364. if(settings["session"]["spectate"].Bool())
  365. {
  366. playerEnvironments[PlayerColor::SPECTATOR] = std::make_shared<CPlayerEnvironment>(PlayerColor::SPECTATOR, this, std::make_shared<CCallback>(gs, boost::none, this));
  367. }
  368. }
  369. void CClient::initPlayerInterfaces()
  370. {
  371. for(auto & elem : gs->scenarioOps->playerInfos)
  372. {
  373. PlayerColor color = elem.first;
  374. if(!vstd::contains(CSH->getAllClientPlayers(CSH->c->connectionID), color))
  375. continue;
  376. if(!vstd::contains(playerint, color))
  377. {
  378. logNetwork->info("Preparing interface for player %s", color.getStr());
  379. if(elem.second.isControlledByAI())
  380. {
  381. auto AiToGive = aiNameForPlayer(elem.second, false);
  382. logNetwork->info("Player %s will be lead by %s", color.getStr(), AiToGive);
  383. installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color);
  384. }
  385. else
  386. {
  387. logNetwork->info("Player %s will be lead by human", color.getStr());
  388. installNewPlayerInterface(std::make_shared<CPlayerInterface>(color), color);
  389. }
  390. }
  391. }
  392. if(settings["session"]["spectate"].Bool())
  393. {
  394. installNewPlayerInterface(std::make_shared<CPlayerInterface>(PlayerColor::SPECTATOR), PlayerColor::SPECTATOR, true);
  395. }
  396. if(CSH->getAllClientPlayers(CSH->c->connectionID).count(PlayerColor::NEUTRAL))
  397. installNewBattleInterface(CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String()), PlayerColor::NEUTRAL);
  398. logNetwork->trace("Initialized player interfaces %d ms", CSH->th->getDiff());
  399. }
  400. std::string CClient::aiNameForPlayer(const PlayerSettings & ps, bool battleAI)
  401. {
  402. if(ps.name.size())
  403. {
  404. const boost::filesystem::path aiPath = VCMIDirs::get().fullLibraryPath("AI", ps.name);
  405. if(boost::filesystem::exists(aiPath))
  406. return ps.name;
  407. }
  408. return aiNameForPlayer(battleAI);
  409. }
  410. std::string CClient::aiNameForPlayer(bool battleAI)
  411. {
  412. const int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
  413. std::string goodAI = battleAI ? settings["server"]["neutralAI"].String() : settings["server"]["playerAI"].String();
  414. std::string badAI = battleAI ? "StupidAI" : "EmptyAI";
  415. //TODO what about human players
  416. if(battleints.size() >= sensibleAILimit)
  417. return badAI;
  418. return goodAI;
  419. }
  420. void CClient::installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, PlayerColor color, bool battlecb)
  421. {
  422. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  423. playerint[color] = gameInterface;
  424. logGlobal->trace("\tInitializing the interface for player %s", color.getStr());
  425. auto cb = std::make_shared<CCallback>(gs, color, this);
  426. battleCallbacks[color] = cb;
  427. gameInterface->initGameInterface(playerEnvironments.at(color), cb);
  428. installNewBattleInterface(gameInterface, color, battlecb);
  429. }
  430. void CClient::installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, PlayerColor color, bool needCallback)
  431. {
  432. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  433. battleints[color] = battleInterface;
  434. if(needCallback)
  435. {
  436. logGlobal->trace("\tInitializing the battle interface for player %s", color.getStr());
  437. auto cbc = std::make_shared<CBattleCallback>(color, this);
  438. battleCallbacks[color] = cbc;
  439. battleInterface->initBattleInterface(playerEnvironments.at(color), cbc);
  440. }
  441. }
  442. void CClient::handlePack(CPack * pack)
  443. {
  444. CBaseForCLApply * apply = applier->getApplier(typeList.getTypeID(pack)); //find the applier
  445. if(apply)
  446. {
  447. boost::unique_lock<boost::recursive_mutex> guiLock(*CPlayerInterface::pim);
  448. apply->applyOnClBefore(this, pack);
  449. logNetwork->trace("\tMade first apply on cl: %s", typeList.getTypeInfo(pack)->name());
  450. gs->apply(pack);
  451. logNetwork->trace("\tApplied on gs: %s", typeList.getTypeInfo(pack)->name());
  452. apply->applyOnClAfter(this, pack);
  453. logNetwork->trace("\tMade second apply on cl: %s", typeList.getTypeInfo(pack)->name());
  454. }
  455. else
  456. {
  457. logNetwork->error("Message %s cannot be applied, cannot find applier!", typeList.getTypeInfo(pack)->name());
  458. }
  459. delete pack;
  460. }
  461. int CClient::sendRequest(const CPackForServer * request, PlayerColor player)
  462. {
  463. static ui32 requestCounter = 0;
  464. ui32 requestID = requestCounter++;
  465. logNetwork->trace("Sending a request \"%s\". It'll have an ID=%d.", typeid(*request).name(), requestID);
  466. waitingRequest.pushBack(requestID);
  467. request->requestID = requestID;
  468. request->player = player;
  469. CSH->c->sendPack(request);
  470. if(vstd::contains(playerint, player))
  471. playerint[player]->requestSent(request, requestID);
  472. return requestID;
  473. }
  474. void CClient::battleStarted(const BattleInfo * info)
  475. {
  476. setBattle(info);
  477. for(auto & battleCb : battleCallbacks)
  478. {
  479. if(vstd::contains_if(info->sides, [&](const SideInBattle& side) {return side.color == battleCb.first; })
  480. || battleCb.first >= PlayerColor::PLAYER_LIMIT)
  481. {
  482. battleCb.second->setBattle(info);
  483. }
  484. }
  485. std::shared_ptr<CPlayerInterface> att, def;
  486. auto & leftSide = info->sides[0], & rightSide = info->sides[1];
  487. //If quick combat is not, do not prepare interfaces for battleint
  488. if(!settings["adventure"]["quickCombat"].Bool())
  489. {
  490. if(vstd::contains(playerint, leftSide.color) && playerint[leftSide.color]->human)
  491. att = std::dynamic_pointer_cast<CPlayerInterface>(playerint[leftSide.color]);
  492. if(vstd::contains(playerint, rightSide.color) && playerint[rightSide.color]->human)
  493. def = std::dynamic_pointer_cast<CPlayerInterface>(playerint[rightSide.color]);
  494. }
  495. if(!settings["session"]["headless"].Bool())
  496. {
  497. if(!!att || !!def)
  498. {
  499. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  500. CPlayerInterface::battleInt = std::make_shared<BattleInterface>(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, att, def);
  501. }
  502. else if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  503. {
  504. //TODO: This certainly need improvement
  505. auto spectratorInt = std::dynamic_pointer_cast<CPlayerInterface>(playerint[PlayerColor::SPECTATOR]);
  506. spectratorInt->cb->setBattle(info);
  507. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  508. CPlayerInterface::battleInt = std::make_shared<BattleInterface>(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, att, def, spectratorInt);
  509. }
  510. }
  511. auto callBattleStart = [&](PlayerColor color, ui8 side)
  512. {
  513. if(vstd::contains(battleints, color))
  514. battleints[color]->battleStart(leftSide.armyObject, rightSide.armyObject, info->tile, leftSide.hero, rightSide.hero, side);
  515. };
  516. callBattleStart(leftSide.color, 0);
  517. callBattleStart(rightSide.color, 1);
  518. callBattleStart(PlayerColor::UNFLAGGABLE, 1);
  519. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  520. callBattleStart(PlayerColor::SPECTATOR, 1);
  521. if(info->tacticDistance && vstd::contains(battleints, info->sides[info->tacticsSide].color))
  522. {
  523. boost::thread(&CClient::commenceTacticPhaseForInt, this, battleints[info->sides[info->tacticsSide].color]);
  524. }
  525. }
  526. void CClient::commenceTacticPhaseForInt(std::shared_ptr<CBattleGameInterface> battleInt)
  527. {
  528. setThreadName("CClient::commenceTacticPhaseForInt");
  529. try
  530. {
  531. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  532. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  533. {
  534. MakeAction ma(BattleAction::makeEndOFTacticPhase(gs->curB->playerToSide(battleInt->playerID).get()));
  535. sendRequest(&ma, battleInt->playerID);
  536. }
  537. }
  538. catch(...)
  539. {
  540. handleException();
  541. }
  542. }
  543. void CClient::battleFinished()
  544. {
  545. stopAllBattleActions();
  546. for(auto & side : gs->curB->sides)
  547. if(battleCallbacks.count(side.color))
  548. battleCallbacks[side.color]->setBattle(nullptr);
  549. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  550. battleCallbacks[PlayerColor::SPECTATOR]->setBattle(nullptr);
  551. setBattle(nullptr);
  552. }
  553. void CClient::startPlayerBattleAction(PlayerColor color)
  554. {
  555. stopPlayerBattleAction(color);
  556. if(vstd::contains(battleints, color))
  557. {
  558. auto thread = std::make_shared<boost::thread>(std::bind(&CClient::waitForMoveAndSend, this, color));
  559. playerActionThreads[color] = thread;
  560. }
  561. }
  562. void CClient::stopPlayerBattleAction(PlayerColor color)
  563. {
  564. if(vstd::contains(playerActionThreads, color))
  565. {
  566. auto thread = playerActionThreads.at(color);
  567. if(thread->joinable())
  568. {
  569. thread->interrupt();
  570. thread->join();
  571. }
  572. playerActionThreads.erase(color);
  573. }
  574. }
  575. void CClient::stopAllBattleActions()
  576. {
  577. while(!playerActionThreads.empty())
  578. stopPlayerBattleAction(playerActionThreads.begin()->first);
  579. }
  580. void CClient::waitForMoveAndSend(PlayerColor color)
  581. {
  582. try
  583. {
  584. setThreadName("CClient::waitForMoveAndSend");
  585. assert(vstd::contains(battleints, color));
  586. BattleAction ba = battleints[color]->activeStack(gs->curB->battleGetStackByID(gs->curB->activeStack, false));
  587. if(ba.actionType != EActionType::CANCEL)
  588. {
  589. logNetwork->trace("Send battle action to server: %s", ba.toString());
  590. MakeAction temp_action(ba);
  591. sendRequest(&temp_action, color);
  592. }
  593. }
  594. catch(boost::thread_interrupted &)
  595. {
  596. logNetwork->debug("Wait for move thread was interrupted and no action will be send. Was a battle ended by spell?");
  597. }
  598. catch(...)
  599. {
  600. handleException();
  601. }
  602. }
  603. void CClient::invalidatePaths()
  604. {
  605. boost::unique_lock<boost::mutex> pathLock(pathCacheMutex);
  606. pathCache.clear();
  607. }
  608. std::shared_ptr<const CPathsInfo> CClient::getPathsInfo(const CGHeroInstance * h)
  609. {
  610. assert(h);
  611. boost::unique_lock<boost::mutex> pathLock(pathCacheMutex);
  612. auto iter = pathCache.find(h);
  613. if(iter == std::end(pathCache))
  614. {
  615. std::shared_ptr<CPathsInfo> paths = std::make_shared<CPathsInfo>(getMapSize(), h);
  616. gs->calculatePaths(h, *paths.get());
  617. pathCache[h] = paths;
  618. return paths;
  619. }
  620. else
  621. {
  622. return iter->second;
  623. }
  624. }
  625. PlayerColor CClient::getLocalPlayer() const
  626. {
  627. if(LOCPLINT)
  628. return LOCPLINT->playerID;
  629. return getCurrentPlayer();
  630. }
  631. #if SCRIPTING_ENABLED
  632. scripting::Pool * CClient::getGlobalContextPool() const
  633. {
  634. return clientScripts.get();
  635. }
  636. scripting::Pool * CClient::getContextPool() const
  637. {
  638. return clientScripts.get();
  639. }
  640. #endif
  641. void CClient::reinitScripting()
  642. {
  643. clientEventBus = std::make_unique<events::EventBus>();
  644. #if SCRIPTING_ENABLED
  645. clientScripts.reset(new scripting::PoolImpl(this));
  646. #endif
  647. }
  648. void CClient::removeGUI()
  649. {
  650. // CClient::endGame
  651. GH.curInt = nullptr;
  652. if(GH.topInt())
  653. GH.topInt()->deactivate();
  654. adventureInt.reset();
  655. GH.listInt.clear();
  656. GH.objsToBlit.clear();
  657. GH.statusbar.reset();
  658. logGlobal->info("Removed GUI.");
  659. LOCPLINT = nullptr;
  660. }
  661. #ifdef VCMI_ANDROID
  662. extern "C" JNIEXPORT void JNICALL Java_eu_vcmi_vcmi_NativeMethods_clientSetupJNI(JNIEnv * env, jobject cls)
  663. {
  664. logNetwork->info("Received clientSetupJNI");
  665. CAndroidVMHelper::cacheVM(env);
  666. }
  667. extern "C" JNIEXPORT void JNICALL Java_eu_vcmi_vcmi_NativeMethods_notifyServerClosed(JNIEnv * env, jobject cls)
  668. {
  669. logNetwork->info("Received server closed signal");
  670. if (CSH) {
  671. CSH->campaignServerRestartLock.setn(false);
  672. }
  673. }
  674. extern "C" JNIEXPORT void JNICALL Java_eu_vcmi_vcmi_NativeMethods_notifyServerReady(JNIEnv * env, jobject cls)
  675. {
  676. logNetwork->info("Received server ready signal");
  677. androidTestServerReadyFlag.store(true);
  678. }
  679. extern "C" JNIEXPORT bool JNICALL Java_eu_vcmi_vcmi_NativeMethods_tryToSaveTheGame(JNIEnv * env, jobject cls)
  680. {
  681. logGlobal->info("Received emergency save game request");
  682. if(!LOCPLINT || !LOCPLINT->cb)
  683. {
  684. return false;
  685. }
  686. LOCPLINT->cb->save("Saves/_Android_Autosave");
  687. return true;
  688. }
  689. #endif