Client.cpp 20 KB

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