Client.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  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 "Global.h"
  11. #include "StdInc.h"
  12. #include "Client.h"
  13. #include "CGameInfo.h"
  14. #include "CPlayerInterface.h"
  15. #include "CServerHandler.h"
  16. #include "ClientNetPackVisitors.h"
  17. #include "adventureMap/AdventureMapInterface.h"
  18. #include "battle/BattleInterface.h"
  19. #include "gui/CGuiHandler.h"
  20. #include "gui/WindowHandler.h"
  21. #include "mapView/mapHandler.h"
  22. #include "../CCallback.h"
  23. #include "../lib/CConfigHandler.h"
  24. #include "../lib/gameState/CGameState.h"
  25. #include "../lib/CThreadHelper.h"
  26. #include "../lib/VCMIDirs.h"
  27. #include "../lib/UnlockGuard.h"
  28. #include "../lib/battle/BattleInfo.h"
  29. #include "../lib/serializer/BinaryDeserializer.h"
  30. #include "../lib/mapping/CMapService.h"
  31. #include "../lib/pathfinder/CGPathNode.h"
  32. #include "../lib/filesystem/Filesystem.h"
  33. #include "../lib/registerTypes/RegisterTypes.h"
  34. #include "../lib/serializer/Connection.h"
  35. #include <memory>
  36. #include <vcmi/events/EventBus.h>
  37. #if SCRIPTING_ENABLED
  38. #include "../lib/ScriptHandler.h"
  39. #endif
  40. #ifdef VCMI_ANDROID
  41. #include "lib/CAndroidVMHelper.h"
  42. #ifndef SINGLE_PROCESS_APP
  43. std::atomic_bool androidTestServerReadyFlag;
  44. #endif
  45. #endif
  46. ThreadSafeVector<int> CClient::waitingRequest;
  47. template<typename T> class CApplyOnCL;
  48. class CBaseForCLApply
  49. {
  50. public:
  51. virtual void applyOnClAfter(CClient * cl, void * pack) const =0;
  52. virtual void applyOnClBefore(CClient * cl, void * pack) const =0;
  53. virtual ~CBaseForCLApply(){}
  54. template<typename U> static CBaseForCLApply * getApplier(const U * t = nullptr)
  55. {
  56. return new CApplyOnCL<U>();
  57. }
  58. };
  59. template<typename T> class CApplyOnCL : public CBaseForCLApply
  60. {
  61. public:
  62. void applyOnClAfter(CClient * cl, void * pack) const override
  63. {
  64. T * ptr = static_cast<T *>(pack);
  65. ApplyClientNetPackVisitor visitor(*cl, *cl->gameState());
  66. ptr->visit(visitor);
  67. }
  68. void applyOnClBefore(CClient * cl, void * pack) const override
  69. {
  70. T * ptr = static_cast<T *>(pack);
  71. ApplyFirstClientNetPackVisitor visitor(*cl, *cl->gameState());
  72. ptr->visit(visitor);
  73. }
  74. };
  75. template<> class CApplyOnCL<CPack>: public CBaseForCLApply
  76. {
  77. public:
  78. void applyOnClAfter(CClient * cl, void * pack) const override
  79. {
  80. logGlobal->error("Cannot apply on CL plain CPack!");
  81. assert(0);
  82. }
  83. void applyOnClBefore(CClient * cl, void * pack) const override
  84. {
  85. logGlobal->error("Cannot apply on CL plain CPack!");
  86. assert(0);
  87. }
  88. };
  89. CPlayerEnvironment::CPlayerEnvironment(PlayerColor player_, CClient * cl_, std::shared_ptr<CCallback> mainCallback_)
  90. : player(player_),
  91. cl(cl_),
  92. mainCallback(mainCallback_)
  93. {
  94. }
  95. const Services * CPlayerEnvironment::services() const
  96. {
  97. return VLC;
  98. }
  99. vstd::CLoggerBase * CPlayerEnvironment::logger() const
  100. {
  101. return logGlobal;
  102. }
  103. events::EventBus * CPlayerEnvironment::eventBus() const
  104. {
  105. return cl->eventBus();//always get actual value
  106. }
  107. const CPlayerEnvironment::BattleCb * CPlayerEnvironment::battle() const
  108. {
  109. return mainCallback.get();
  110. }
  111. const CPlayerEnvironment::GameCb * CPlayerEnvironment::game() const
  112. {
  113. return mainCallback.get();
  114. }
  115. CClient::CClient()
  116. {
  117. waitingRequest.clear();
  118. applier = std::make_shared<CApplier<CBaseForCLApply>>();
  119. registerTypesClientPacks1(*applier);
  120. registerTypesClientPacks2(*applier);
  121. IObjectInterface::cb = this;
  122. gs = nullptr;
  123. }
  124. CClient::~CClient()
  125. {
  126. IObjectInterface::cb = nullptr;
  127. }
  128. const Services * CClient::services() const
  129. {
  130. return VLC; //todo: this should be CGI
  131. }
  132. const CClient::BattleCb * CClient::battle() const
  133. {
  134. return this;
  135. }
  136. const CClient::GameCb * CClient::game() const
  137. {
  138. return this;
  139. }
  140. vstd::CLoggerBase * CClient::logger() const
  141. {
  142. return logGlobal;
  143. }
  144. events::EventBus * CClient::eventBus() const
  145. {
  146. return clientEventBus.get();
  147. }
  148. void CClient::newGame(CGameState * initializedGameState)
  149. {
  150. CSH->th->update();
  151. CMapService mapService;
  152. gs = initializedGameState ? initializedGameState : new CGameState();
  153. gs->preInit(VLC);
  154. logNetwork->trace("\tCreating gamestate: %i", CSH->th->getDiff());
  155. if(!initializedGameState)
  156. {
  157. Load::ProgressAccumulator progressTracking;
  158. gs->init(&mapService, CSH->si.get(), progressTracking, settings["general"]["saveRandomMaps"].Bool());
  159. }
  160. logNetwork->trace("Initializing GameState (together): %d ms", CSH->th->getDiff());
  161. initMapHandler();
  162. reinitScripting();
  163. initPlayerEnvironments();
  164. initPlayerInterfaces();
  165. }
  166. void CClient::loadGame(CGameState * initializedGameState)
  167. {
  168. logNetwork->info("Loading procedure started!");
  169. logNetwork->info("Game state was transferred over network, loading.");
  170. gs = initializedGameState;
  171. gs->preInit(VLC);
  172. gs->updateOnLoad(CSH->si.get());
  173. logNetwork->info("Game loaded, initialize interfaces.");
  174. initMapHandler();
  175. reinitScripting();
  176. initPlayerEnvironments();
  177. // Loading of client state - disabled for now
  178. // Since client no longer writes or loads its own state and instead receives it from server
  179. // client state serializer will serialize its own copies of all pointers, e.g. heroes/towns/objects
  180. // and on deserialize will create its own copies (instead of using copies from state received from server)
  181. // Potential solutions:
  182. // 1) Use server gamestate to deserialize pointers, so any pointer to same object will point to server instance and not our copy
  183. // 2) Remove all serialization of pointers with instance ID's and restore them on load (including AI deserializer code)
  184. // 3) Completely remove client savegame and send all information, like hero paths and sleeping status to server (either in form of hero properties or as some generic "client options" message
  185. #ifdef BROKEN_CLIENT_STATE_SERIALIZATION_HAS_BEEN_FIXED
  186. // try to deserialize client data including sleepingHeroes
  187. try
  188. {
  189. boost::filesystem::path clientSaveName = *CResourceHandler::get()->getResourceName(ResourceID(CSH->si->mapname, EResType::CLIENT_SAVEGAME));
  190. if(clientSaveName.empty())
  191. throw std::runtime_error("Cannot open client part of " + CSH->si->mapname);
  192. std::unique_ptr<CLoadFile> loader (new CLoadFile(clientSaveName));
  193. serialize(loader->serializer, loader->serializer.fileVersion);
  194. logNetwork->info("Client data loaded.");
  195. }
  196. catch(std::exception & e)
  197. {
  198. logGlobal->info("Cannot load client data for game %s. Error: %s", CSH->si->mapname, e.what());
  199. }
  200. #endif
  201. initPlayerInterfaces();
  202. }
  203. void CClient::serialize(BinarySerializer & h, const int version)
  204. {
  205. assert(h.saving);
  206. ui8 players = static_cast<ui8>(playerint.size());
  207. h & players;
  208. for(auto i = playerint.begin(); i != playerint.end(); i++)
  209. {
  210. logGlobal->trace("Saving player %s interface", i->first);
  211. assert(i->first == i->second->playerID);
  212. h & i->first;
  213. h & i->second->dllName;
  214. h & i->second->human;
  215. i->second->saveGame(h, version);
  216. }
  217. #if SCRIPTING_ENABLED
  218. if(version >= 800)
  219. {
  220. JsonNode scriptsState;
  221. clientScripts->serializeState(h.saving, scriptsState);
  222. h & scriptsState;
  223. }
  224. #endif
  225. }
  226. void CClient::serialize(BinaryDeserializer & h, const int version)
  227. {
  228. assert(!h.saving);
  229. ui8 players = 0;
  230. h & players;
  231. for(int i = 0; i < players; i++)
  232. {
  233. std::string dllname;
  234. PlayerColor pid;
  235. bool isHuman = false;
  236. auto prevInt = LOCPLINT;
  237. h & pid;
  238. h & dllname;
  239. h & isHuman;
  240. assert(dllname.length() == 0 || !isHuman);
  241. if(pid == PlayerColor::NEUTRAL)
  242. {
  243. logGlobal->trace("Neutral battle interfaces are not serialized.");
  244. continue;
  245. }
  246. logGlobal->trace("Loading player %s interface", pid);
  247. std::shared_ptr<CGameInterface> nInt;
  248. if(dllname.length())
  249. nInt = CDynLibHandler::getNewAI(dllname);
  250. else
  251. nInt = std::make_shared<CPlayerInterface>(pid);
  252. nInt->dllName = dllname;
  253. nInt->human = isHuman;
  254. nInt->playerID = pid;
  255. bool shouldResetInterface = true;
  256. // Client no longer handle this player at all
  257. if(!vstd::contains(CSH->getAllClientPlayers(CSH->c->connectionID), pid))
  258. {
  259. logGlobal->trace("Player %s is not belong to this client. Destroying interface", pid);
  260. }
  261. else if(isHuman && !vstd::contains(CSH->getHumanColors(), pid))
  262. {
  263. logGlobal->trace("Player %s is no longer controlled by human. Destroying interface", pid);
  264. }
  265. else if(!isHuman && vstd::contains(CSH->getHumanColors(), pid))
  266. {
  267. logGlobal->trace("Player %s is no longer controlled by AI. Destroying interface", pid);
  268. }
  269. else
  270. {
  271. installNewPlayerInterface(nInt, pid);
  272. shouldResetInterface = false;
  273. }
  274. // loadGame needs to be called after initGameInterface to load paths correctly
  275. // initGameInterface is called in installNewPlayerInterface
  276. nInt->loadGame(h, version);
  277. if (shouldResetInterface)
  278. {
  279. nInt.reset();
  280. LOCPLINT = prevInt;
  281. }
  282. }
  283. #if SCRIPTING_ENABLED
  284. {
  285. JsonNode scriptsState;
  286. h & scriptsState;
  287. clientScripts->serializeState(h.saving, scriptsState);
  288. }
  289. #endif
  290. logNetwork->trace("Loaded client part of save %d ms", CSH->th->getDiff());
  291. }
  292. void CClient::save(const std::string & fname)
  293. {
  294. if(gs->curB)
  295. {
  296. logNetwork->error("Game cannot be saved during battle!");
  297. return;
  298. }
  299. SaveGame save_game(fname);
  300. sendRequest(&save_game, PlayerColor::NEUTRAL);
  301. }
  302. void CClient::endGame()
  303. {
  304. #if SCRIPTING_ENABLED
  305. clientScripts.reset();
  306. #endif
  307. //suggest interfaces to finish their stuff (AI should interrupt any bg working threads)
  308. for(auto & i : playerint)
  309. i.second->finish();
  310. GH.curInt = nullptr;
  311. {
  312. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  313. logNetwork->info("Ending current game!");
  314. removeGUI();
  315. vstd::clear_pointer(const_cast<CGameInfo *>(CGI)->mh);
  316. vstd::clear_pointer(gs);
  317. logNetwork->info("Deleted mapHandler and gameState.");
  318. }
  319. CPlayerInterface::battleInt.reset();
  320. playerint.clear();
  321. battleints.clear();
  322. battleCallbacks.clear();
  323. playerEnvironments.clear();
  324. logNetwork->info("Deleted playerInts.");
  325. logNetwork->info("Client stopped.");
  326. }
  327. void CClient::initMapHandler()
  328. {
  329. // TODO: CMapHandler initialization can probably go somewhere else
  330. // It's can't be before initialization of interfaces
  331. // During loading CPlayerInterface from serialized state it's depend on MH
  332. if(!settings["session"]["headless"].Bool())
  333. {
  334. const_cast<CGameInfo *>(CGI)->mh = new CMapHandler(gs->map);
  335. logNetwork->trace("Creating mapHandler: %d ms", CSH->th->getDiff());
  336. }
  337. pathCache.clear();
  338. }
  339. void CClient::initPlayerEnvironments()
  340. {
  341. playerEnvironments.clear();
  342. auto allPlayers = CSH->getAllClientPlayers(CSH->c->connectionID);
  343. bool hasHumanPlayer = false;
  344. for(auto & color : allPlayers)
  345. {
  346. logNetwork->info("Preparing environment for player %s", color.toString());
  347. playerEnvironments[color] = std::make_shared<CPlayerEnvironment>(color, this, std::make_shared<CCallback>(gs, color, this));
  348. if(!hasHumanPlayer && gs->players[color].isHuman())
  349. hasHumanPlayer = true;
  350. }
  351. if(!hasHumanPlayer)
  352. {
  353. Settings session = settings.write["session"];
  354. session["spectate"].Bool() = true;
  355. session["spectate-skip-battle-result"].Bool() = true;
  356. session["spectate-ignore-hero"].Bool() = true;
  357. }
  358. if(settings["session"]["spectate"].Bool())
  359. {
  360. playerEnvironments[PlayerColor::SPECTATOR] = std::make_shared<CPlayerEnvironment>(PlayerColor::SPECTATOR, this, std::make_shared<CCallback>(gs, std::nullopt, this));
  361. }
  362. }
  363. void CClient::initPlayerInterfaces()
  364. {
  365. for(auto & playerInfo : gs->scenarioOps->playerInfos)
  366. {
  367. PlayerColor color = playerInfo.first;
  368. if(!vstd::contains(CSH->getAllClientPlayers(CSH->c->connectionID), color))
  369. continue;
  370. if(!vstd::contains(playerint, color))
  371. {
  372. logNetwork->info("Preparing interface for player %s", color.toString());
  373. if(playerInfo.second.isControlledByAI())
  374. {
  375. bool alliedToHuman = false;
  376. for(auto & allyInfo : gs->scenarioOps->playerInfos)
  377. if (gs->getPlayerTeam(allyInfo.first) == gs->getPlayerTeam(playerInfo.first) && allyInfo.second.isControlledByHuman())
  378. alliedToHuman = true;
  379. auto AiToGive = aiNameForPlayer(playerInfo.second, false, alliedToHuman);
  380. logNetwork->info("Player %s will be lead by %s", color.toString(), AiToGive);
  381. installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color);
  382. }
  383. else
  384. {
  385. logNetwork->info("Player %s will be lead by human", color.toString());
  386. installNewPlayerInterface(std::make_shared<CPlayerInterface>(color), color);
  387. }
  388. }
  389. }
  390. if(settings["session"]["spectate"].Bool())
  391. {
  392. installNewPlayerInterface(std::make_shared<CPlayerInterface>(PlayerColor::SPECTATOR), PlayerColor::SPECTATOR, true);
  393. }
  394. if(CSH->getAllClientPlayers(CSH->c->connectionID).count(PlayerColor::NEUTRAL))
  395. installNewBattleInterface(CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String()), PlayerColor::NEUTRAL);
  396. logNetwork->trace("Initialized player interfaces %d ms", CSH->th->getDiff());
  397. }
  398. std::string CClient::aiNameForPlayer(const PlayerSettings & ps, bool battleAI, bool alliedToHuman)
  399. {
  400. if(ps.name.size())
  401. {
  402. const boost::filesystem::path aiPath = VCMIDirs::get().fullLibraryPath("AI", ps.name);
  403. if(boost::filesystem::exists(aiPath))
  404. return ps.name;
  405. }
  406. return aiNameForPlayer(battleAI, alliedToHuman);
  407. }
  408. std::string CClient::aiNameForPlayer(bool battleAI, bool alliedToHuman)
  409. {
  410. const int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
  411. std::string goodAdventureAI = alliedToHuman ? settings["server"]["alliedAI"].String() : settings["server"]["playerAI"].String();
  412. std::string goodBattleAI = settings["server"]["neutralAI"].String();
  413. std::string goodAI = battleAI ? goodBattleAI : goodAdventureAI;
  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.toString());
  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.toString());
  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.isValidPlayer())
  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. auto callBattleStart = [&](PlayerColor color, ui8 side)
  489. {
  490. if(vstd::contains(battleints, color))
  491. battleints[color]->battleStart(leftSide.armyObject, rightSide.armyObject, info->tile, leftSide.hero, rightSide.hero, side, info->replayAllowed);
  492. };
  493. callBattleStart(leftSide.color, 0);
  494. callBattleStart(rightSide.color, 1);
  495. callBattleStart(PlayerColor::UNFLAGGABLE, 1);
  496. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  497. callBattleStart(PlayerColor::SPECTATOR, 1);
  498. if(vstd::contains(playerint, leftSide.color) && playerint[leftSide.color]->human)
  499. att = std::dynamic_pointer_cast<CPlayerInterface>(playerint[leftSide.color]);
  500. if(vstd::contains(playerint, rightSide.color) && playerint[rightSide.color]->human)
  501. def = std::dynamic_pointer_cast<CPlayerInterface>(playerint[rightSide.color]);
  502. //Remove player interfaces for auto battle (quickCombat option)
  503. if(att && att->isAutoFightOn)
  504. {
  505. if (att->cb->battleGetTacticDist())
  506. {
  507. auto side = att->cb->playerToSide(att->playerID);
  508. auto action = BattleAction::makeEndOFTacticPhase(*side);
  509. att->cb->battleMakeTacticAction(action);
  510. }
  511. att.reset();
  512. def.reset();
  513. }
  514. if(!settings["session"]["headless"].Bool())
  515. {
  516. if(att || def)
  517. {
  518. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  519. CPlayerInterface::battleInt = std::make_shared<BattleInterface>(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, att, def);
  520. }
  521. else if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  522. {
  523. //TODO: This certainly need improvement
  524. auto spectratorInt = std::dynamic_pointer_cast<CPlayerInterface>(playerint[PlayerColor::SPECTATOR]);
  525. spectratorInt->cb->setBattle(info);
  526. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  527. CPlayerInterface::battleInt = std::make_shared<BattleInterface>(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, att, def, spectratorInt);
  528. }
  529. }
  530. if(info->tacticDistance)
  531. {
  532. auto tacticianColor = info->sides[info->tacticsSide].color;
  533. if (vstd::contains(battleints, tacticianColor))
  534. battleints[tacticianColor]->yourTacticPhase(info->tacticDistance);
  535. }
  536. }
  537. void CClient::battleFinished()
  538. {
  539. for(auto & side : gs->curB->sides)
  540. if(battleCallbacks.count(side.color))
  541. battleCallbacks[side.color]->setBattle(nullptr);
  542. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  543. battleCallbacks[PlayerColor::SPECTATOR]->setBattle(nullptr);
  544. setBattle(nullptr);
  545. gs->curB.dellNull();
  546. }
  547. void CClient::startPlayerBattleAction(PlayerColor color)
  548. {
  549. assert(vstd::contains(battleints, color));
  550. if(vstd::contains(battleints, color))
  551. {
  552. // we want to avoid locking gamestate and causing UI to freeze while AI is making turn
  553. auto unlock = vstd::makeUnlockGuardIf(*CPlayerInterface::pim, !battleints[color]->human);
  554. assert(vstd::contains(battleints, color));
  555. battleints[color]->activeStack(gs->curB->battleGetStackByID(gs->curB->activeStack, false));
  556. }
  557. }
  558. void CClient::invalidatePaths()
  559. {
  560. boost::unique_lock<boost::mutex> pathLock(pathCacheMutex);
  561. pathCache.clear();
  562. }
  563. std::shared_ptr<const CPathsInfo> CClient::getPathsInfo(const CGHeroInstance * h)
  564. {
  565. assert(h);
  566. boost::unique_lock<boost::mutex> pathLock(pathCacheMutex);
  567. auto iter = pathCache.find(h);
  568. if(iter == std::end(pathCache))
  569. {
  570. std::shared_ptr<CPathsInfo> paths = std::make_shared<CPathsInfo>(getMapSize(), h);
  571. gs->calculatePaths(h, *paths.get());
  572. pathCache[h] = paths;
  573. return paths;
  574. }
  575. else
  576. {
  577. return iter->second;
  578. }
  579. }
  580. #if SCRIPTING_ENABLED
  581. scripting::Pool * CClient::getGlobalContextPool() const
  582. {
  583. return clientScripts.get();
  584. }
  585. scripting::Pool * CClient::getContextPool() const
  586. {
  587. return clientScripts.get();
  588. }
  589. #endif
  590. void CClient::reinitScripting()
  591. {
  592. clientEventBus = std::make_unique<events::EventBus>();
  593. #if SCRIPTING_ENABLED
  594. clientScripts.reset(new scripting::PoolImpl(this));
  595. #endif
  596. }
  597. void CClient::removeGUI()
  598. {
  599. // CClient::endGame
  600. GH.curInt = nullptr;
  601. GH.windows().clear();
  602. adventureInt.reset();
  603. logGlobal->info("Removed GUI.");
  604. LOCPLINT = nullptr;
  605. }
  606. #ifdef VCMI_ANDROID
  607. #ifndef SINGLE_PROCESS_APP
  608. extern "C" JNIEXPORT void JNICALL Java_eu_vcmi_vcmi_NativeMethods_notifyServerClosed(JNIEnv * env, jclass cls)
  609. {
  610. logNetwork->info("Received server closed signal");
  611. if (CSH) {
  612. CSH->campaignServerRestartLock.setn(false);
  613. }
  614. }
  615. extern "C" JNIEXPORT void JNICALL Java_eu_vcmi_vcmi_NativeMethods_notifyServerReady(JNIEnv * env, jclass cls)
  616. {
  617. logNetwork->info("Received server ready signal");
  618. androidTestServerReadyFlag.store(true);
  619. }
  620. #endif
  621. extern "C" JNIEXPORT jboolean JNICALL Java_eu_vcmi_vcmi_NativeMethods_tryToSaveTheGame(JNIEnv * env, jclass cls)
  622. {
  623. logGlobal->info("Received emergency save game request");
  624. if(!LOCPLINT || !LOCPLINT->cb)
  625. {
  626. return false;
  627. }
  628. LOCPLINT->cb->save("Saves/_Android_Autosave");
  629. return true;
  630. }
  631. #endif