Client.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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 "Global.h"
  12. #include "Client.h"
  13. #include "CPlayerInterface.h"
  14. #include "PlayerLocalState.h"
  15. #include "CServerHandler.h"
  16. #include "ClientNetPackVisitors.h"
  17. #include "adventureMap/AdventureMapInterface.h"
  18. #include "battle/BattleInterface.h"
  19. #include "GameEngine.h"
  20. #include "GameInstance.h"
  21. #include "gui/WindowHandler.h"
  22. #include "mapView/mapHandler.h"
  23. #include "../lib/CConfigHandler.h"
  24. #include "../lib/GameLibrary.h"
  25. #include "../lib/battle/BattleInfo.h"
  26. #include "../lib/battle/CPlayerBattleCallback.h"
  27. #include "../lib/callback/CCallback.h"
  28. #include "../lib/callback/CDynLibHandler.h"
  29. #include "../lib/callback/CGlobalAI.h"
  30. #include "../lib/callback/IGameInfoCallback.h"
  31. #include "../lib/filesystem/Filesystem.h"
  32. #include "../lib/gameState/CGameState.h"
  33. #include "../lib/CPlayerState.h"
  34. #include "../lib/CThreadHelper.h"
  35. #include "../lib/VCMIDirs.h"
  36. #include "../lib/UnlockGuard.h"
  37. #include "../lib/mapObjects/army/CArmedInstance.h"
  38. #include "../lib/mapping/CMapService.h"
  39. #include "../lib/pathfinder/CGPathNode.h"
  40. #include "../lib/serializer/GameConnection.h"
  41. #include <memory>
  42. #include <vcmi/events/EventBus.h>
  43. #if SCRIPTING_ENABLED
  44. #include "../lib/ScriptHandler.h"
  45. #endif
  46. #ifdef VCMI_ANDROID
  47. #include "lib/CAndroidVMHelper.h"
  48. #endif
  49. CPlayerEnvironment::CPlayerEnvironment(PlayerColor player_, CClient * cl_, std::shared_ptr<CCallback> mainCallback_)
  50. : player(player_),
  51. cl(cl_),
  52. mainCallback(mainCallback_)
  53. {
  54. }
  55. const Services * CPlayerEnvironment::services() const
  56. {
  57. return LIBRARY;
  58. }
  59. vstd::CLoggerBase * CPlayerEnvironment::logger() const
  60. {
  61. return logGlobal;
  62. }
  63. events::EventBus * CPlayerEnvironment::eventBus() const
  64. {
  65. return cl->eventBus();//always get actual value
  66. }
  67. const CPlayerEnvironment::BattleCb * CPlayerEnvironment::battle(const BattleID & battleID) const
  68. {
  69. return mainCallback->getBattle(battleID).get();
  70. }
  71. const CPlayerEnvironment::GameCb * CPlayerEnvironment::game() const
  72. {
  73. return mainCallback.get();
  74. }
  75. CClient::CClient()
  76. {
  77. waitingRequest.clear();
  78. }
  79. CClient::~CClient() = default;
  80. IGameInfoCallback & CClient::gameInfo()
  81. {
  82. return *gamestate;
  83. }
  84. const Services * CClient::services() const
  85. {
  86. return LIBRARY; //todo: this should be LIBRARY
  87. }
  88. const CClient::BattleCb * CClient::battle(const BattleID & battleID) const
  89. {
  90. return nullptr; //todo?
  91. }
  92. const CClient::GameCb * CClient::game() const
  93. {
  94. return gamestate.get();
  95. }
  96. vstd::CLoggerBase * CClient::logger() const
  97. {
  98. return logGlobal;
  99. }
  100. events::EventBus * CClient::eventBus() const
  101. {
  102. return clientEventBus.get();
  103. }
  104. void CClient::newGame(std::shared_ptr<CGameState> initializedGameState)
  105. {
  106. GAME->server().th->update();
  107. assert(initializedGameState);
  108. gamestate = initializedGameState;
  109. gamestate->preInit(LIBRARY);
  110. logNetwork->trace("\tCreating gamestate: %i", GAME->server().th->getDiff());
  111. initMapHandler();
  112. reinitScripting();
  113. initPlayerEnvironments();
  114. initPlayerInterfaces();
  115. }
  116. void CClient::loadGame(std::shared_ptr<CGameState> initializedGameState)
  117. {
  118. logNetwork->info("Loading procedure started!");
  119. logNetwork->info("Game state was transferred over network, loading.");
  120. gamestate = initializedGameState;
  121. gamestate->preInit(LIBRARY);
  122. gamestate->updateOnLoad(*GAME->server().si);
  123. logNetwork->info("Game loaded, initialize interfaces.");
  124. initMapHandler();
  125. reinitScripting();
  126. initPlayerEnvironments();
  127. initPlayerInterfaces();
  128. }
  129. void CClient::endNetwork()
  130. {
  131. GAME->map().endNetwork();
  132. if (CPlayerInterface::battleInt)
  133. CPlayerInterface::battleInt->endNetwork();
  134. for(auto & i : playerint)
  135. {
  136. auto interface = std::dynamic_pointer_cast<CPlayerInterface>(i.second);
  137. if (interface)
  138. interface->endNetwork();
  139. }
  140. }
  141. void CClient::finishGameplay()
  142. {
  143. waitingRequest.requestTermination();
  144. //suggest interfaces to finish their stuff (AI should interrupt any bg working threads)
  145. for(auto & i : playerint)
  146. i.second->finish();
  147. }
  148. void CClient::endGame()
  149. {
  150. #if SCRIPTING_ENABLED
  151. clientScripts.reset();
  152. #endif
  153. logNetwork->info("Ending current game!");
  154. removeGUI();
  155. GAME->setMapInstance(nullptr);
  156. logNetwork->info("Deleted mapHandler and gameState.");
  157. CPlayerInterface::battleInt.reset();
  158. playerint.clear();
  159. battleints.clear();
  160. battleCallbacks.clear();
  161. playerEnvironments.clear();
  162. //FIXME: gamestate->currentBattles.clear() will use gamestate. So it shoule be callded before gamestate.reset()
  163. gamestate->currentBattles.clear();
  164. gamestate.reset();
  165. logNetwork->info("Deleted playerInts.");
  166. logNetwork->info("Client stopped.");
  167. }
  168. void CClient::initMapHandler()
  169. {
  170. // TODO: CMapHandler initialization can probably go somewhere else
  171. // It's can't be before initialization of interfaces
  172. // During loading CPlayerInterface from serialized state it's depend on MH
  173. if(!settings["session"]["headless"].Bool())
  174. {
  175. GAME->setMapInstance(std::make_unique<CMapHandler>(&gameState().getMap()));
  176. logNetwork->trace("Creating mapHandler: %d ms", GAME->server().th->getDiff());
  177. }
  178. }
  179. void CClient::initPlayerEnvironments()
  180. {
  181. playerEnvironments.clear();
  182. auto allPlayers = GAME->server().getAllClientPlayers(GAME->server().logicConnection->connectionID);
  183. bool hasHumanPlayer = false;
  184. for(auto & color : allPlayers)
  185. {
  186. logNetwork->info("Preparing environment for player %s", color.toString());
  187. playerEnvironments[color] = std::make_shared<CPlayerEnvironment>(color, this, std::make_shared<CCallback>(gamestate, color, this));
  188. if(color.isValidPlayer() && !hasHumanPlayer && gameState().players.at(color).isHuman())
  189. hasHumanPlayer = true;
  190. }
  191. if(!hasHumanPlayer && !settings["session"]["headless"].Bool())
  192. {
  193. Settings session = settings.write["session"];
  194. session["spectate"].Bool() = true;
  195. session["spectate-skip-battle-result"].Bool() = true;
  196. session["spectate-ignore-hero"].Bool() = true;
  197. }
  198. if(settings["session"]["spectate"].Bool())
  199. {
  200. playerEnvironments[PlayerColor::SPECTATOR] = std::make_shared<CPlayerEnvironment>(PlayerColor::SPECTATOR, this, std::make_shared<CCallback>(gamestate, std::nullopt, this));
  201. }
  202. }
  203. void CClient::initPlayerInterfaces()
  204. {
  205. for(const auto & playerInfo : gameState().getStartInfo()->playerInfos)
  206. {
  207. PlayerColor color = playerInfo.first;
  208. if(!vstd::contains(GAME->server().getAllClientPlayers(GAME->server().logicConnection->connectionID), color))
  209. continue;
  210. if(!vstd::contains(playerint, color))
  211. {
  212. logNetwork->info("Preparing interface for player %s", color.toString());
  213. if(playerInfo.second.isControlledByAI() || settings["session"]["onlyai"].Bool())
  214. {
  215. bool alliedToHuman = false;
  216. for(const auto & allyInfo : gameState().getStartInfo()->playerInfos)
  217. if (gameState().getPlayerTeam(allyInfo.first) == gameState().getPlayerTeam(playerInfo.first) && allyInfo.second.isControlledByHuman())
  218. alliedToHuman = true;
  219. auto AiToGive = aiNameForPlayer(playerInfo.second, false, alliedToHuman);
  220. logNetwork->info("Player %s will be lead by %s", color.toString(), AiToGive);
  221. installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color);
  222. }
  223. else
  224. {
  225. logNetwork->info("Player %s will be lead by human", color.toString());
  226. installNewPlayerInterface(std::make_shared<CPlayerInterface>(color), color);
  227. }
  228. }
  229. }
  230. if(settings["session"]["spectate"].Bool())
  231. {
  232. installNewPlayerInterface(std::make_shared<CPlayerInterface>(PlayerColor::SPECTATOR), PlayerColor::SPECTATOR, true);
  233. }
  234. if(GAME->server().getAllClientPlayers(GAME->server().logicConnection->connectionID).count(PlayerColor::NEUTRAL))
  235. installNewBattleInterface(CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String()), PlayerColor::NEUTRAL);
  236. logNetwork->trace("Initialized player interfaces %d ms", GAME->server().th->getDiff());
  237. }
  238. std::string CClient::aiNameForPlayer(const PlayerSettings & ps, bool battleAI, bool alliedToHuman) const
  239. {
  240. if(ps.name.size())
  241. {
  242. const boost::filesystem::path aiPath = VCMIDirs::get().fullLibraryPath("AI", ps.name);
  243. if(boost::filesystem::exists(aiPath))
  244. return ps.name;
  245. }
  246. return aiNameForPlayer(battleAI, alliedToHuman);
  247. }
  248. std::string CClient::aiNameForPlayer(bool battleAI, bool alliedToHuman) const
  249. {
  250. const int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
  251. std::string goodAdventureAI = alliedToHuman ? settings["server"]["alliedAI"].String() : settings["server"]["playerAI"].String();
  252. std::string goodBattleAI = settings["server"]["neutralAI"].String();
  253. std::string goodAI = battleAI ? goodBattleAI : goodAdventureAI;
  254. std::string badAI = battleAI ? "StupidAI" : "EmptyAI";
  255. //TODO what about human players
  256. if(battleints.size() >= sensibleAILimit)
  257. return badAI;
  258. return goodAI;
  259. }
  260. void CClient::installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, PlayerColor color, bool battlecb)
  261. {
  262. playerint[color] = gameInterface;
  263. logGlobal->trace("\tInitializing the interface for player %s", color.toString());
  264. auto cb = std::make_shared<CCallback>(gamestate, color, this);
  265. battleCallbacks[color] = cb;
  266. gameInterface->initGameInterface(playerEnvironments.at(color), cb);
  267. installNewBattleInterface(gameInterface, color, battlecb);
  268. }
  269. void CClient::installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, PlayerColor color, bool needCallback)
  270. {
  271. battleints[color] = battleInterface;
  272. if(needCallback)
  273. {
  274. logGlobal->trace("\tInitializing the battle interface for player %s", color.toString());
  275. auto cbc = std::make_shared<CBattleCallback>(color, this);
  276. battleCallbacks[color] = cbc;
  277. battleInterface->initBattleInterface(playerEnvironments.at(color), cbc);
  278. }
  279. }
  280. void CClient::handlePack(CPackForClient & pack)
  281. {
  282. ApplyClientNetPackVisitor afterVisitor(*this, gameState());
  283. ApplyFirstClientNetPackVisitor beforeVisitor(*this, gameState());
  284. pack.visit(beforeVisitor);
  285. logNetwork->trace("\tMade first apply on cl: %s", typeid(pack).name());
  286. {
  287. std::unique_lock lock(CGameState::mutex);
  288. gameState().apply(pack);
  289. }
  290. logNetwork->trace("\tApplied on gs: %s", typeid(pack).name());
  291. pack.visit(afterVisitor);
  292. logNetwork->trace("\tMade second apply on cl: %s", typeid(pack).name());
  293. }
  294. std::optional<BattleAction> CClient::makeSurrenderRetreatDecision(PlayerColor player, const BattleID & battleID, const BattleStateInfoForRetreat & battleState)
  295. {
  296. return playerint[player]->makeSurrenderRetreatDecision(battleID, battleState);
  297. }
  298. int CClient::sendRequest(const CPackForServer & request, PlayerColor player, bool waitTillRealize)
  299. {
  300. ui32 requestID = requestCounter++;
  301. logNetwork->trace("Sending a request \"%s\". It'll have an ID=%d.", typeid(request).name(), requestID);
  302. waitingRequest.pushBack(requestID);
  303. request.requestID = requestID;
  304. request.player = player;
  305. GAME->server().sendGamePack(request);
  306. if(vstd::contains(playerint, player))
  307. playerint[player]->requestSent(&request, requestID);
  308. if(waitTillRealize)
  309. {
  310. logGlobal->trace("We'll wait till request %d is answered.\n", requestID);
  311. auto gsUnlocker = vstd::makeUnlockSharedGuard(CGameState::mutex);
  312. waitingRequest.waitWhileContains(requestID);
  313. }
  314. return requestID;
  315. }
  316. void CClient::battleStarted(const BattleID & battleID)
  317. {
  318. const BattleInfo * info = gameState().getBattle(battleID);
  319. std::shared_ptr<CPlayerInterface> att;
  320. std::shared_ptr<CPlayerInterface> def;
  321. const auto & leftSide = info->getSide(BattleSide::LEFT_SIDE);
  322. const auto & rightSide = info->getSide(BattleSide::RIGHT_SIDE);
  323. for(auto & battleCb : battleCallbacks)
  324. {
  325. if(!battleCb.first.isValidPlayer() || battleCb.first == leftSide.color || battleCb.first == rightSide.color)
  326. battleCb.second->onBattleStarted(info);
  327. }
  328. //If quick combat is not, do not prepare interfaces for battleint
  329. auto callBattleStart = [&](PlayerColor color, BattleSide side)
  330. {
  331. if(vstd::contains(battleints, color))
  332. battleints[color]->battleStart(info->battleID, leftSide.getArmy(), rightSide.getArmy(), info->tile, leftSide.getHero(), rightSide.getHero(), side, info->replayAllowed);
  333. };
  334. callBattleStart(leftSide.color, BattleSide::LEFT_SIDE);
  335. callBattleStart(rightSide.color, BattleSide::RIGHT_SIDE);
  336. callBattleStart(PlayerColor::UNFLAGGABLE, BattleSide::RIGHT_SIDE);
  337. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  338. callBattleStart(PlayerColor::SPECTATOR, BattleSide::RIGHT_SIDE);
  339. if(vstd::contains(playerint, leftSide.color) && playerint[leftSide.color]->human)
  340. att = std::dynamic_pointer_cast<CPlayerInterface>(playerint[leftSide.color]);
  341. if(vstd::contains(playerint, rightSide.color) && playerint[rightSide.color]->human)
  342. def = std::dynamic_pointer_cast<CPlayerInterface>(playerint[rightSide.color]);
  343. //Remove player interfaces for auto battle (quickCombat option)
  344. if((att && att->isAutoFightOn) || (def && def->isAutoFightOn))
  345. {
  346. auto endTacticPhaseIfEligible = [info](const CPlayerInterface * interface)
  347. {
  348. if (interface->cb->getBattle(info->battleID)->battleGetTacticDist())
  349. {
  350. auto side = interface->cb->getBattle(info->battleID)->playerToSide(interface->playerID);
  351. if(interface->playerID == info->getSide(info->tacticsSide).color)
  352. {
  353. auto action = BattleAction::makeEndOFTacticPhase(side);
  354. interface->cb->battleMakeTacticAction(info->battleID, action);
  355. }
  356. }
  357. };
  358. if(att && att->isAutoFightOn)
  359. endTacticPhaseIfEligible(att.get());
  360. else // def && def->isAutoFightOn
  361. endTacticPhaseIfEligible(def.get());
  362. att.reset();
  363. def.reset();
  364. }
  365. if(!settings["session"]["headless"].Bool())
  366. {
  367. if(att || def)
  368. {
  369. CPlayerInterface::battleInt = std::make_shared<BattleInterface>(info->getBattleID(), leftSide.getArmy(), rightSide.getArmy(), leftSide.getHero(), rightSide.getHero(), att, def);
  370. }
  371. else if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  372. {
  373. //TODO: This certainly need improvement
  374. auto spectratorInt = std::dynamic_pointer_cast<CPlayerInterface>(playerint[PlayerColor::SPECTATOR]);
  375. spectratorInt->cb->onBattleStarted(info);
  376. CPlayerInterface::battleInt = std::make_shared<BattleInterface>(info->getBattleID(), leftSide.getArmy(), rightSide.getArmy(), leftSide.getHero(), rightSide.getHero(), att, def, spectratorInt);
  377. }
  378. }
  379. if(info->tacticDistance)
  380. {
  381. auto tacticianColor = info->getSide(info->tacticsSide).color;
  382. if (vstd::contains(battleints, tacticianColor))
  383. battleints[tacticianColor]->yourTacticPhase(info->battleID, info->tacticDistance);
  384. }
  385. }
  386. void CClient::battleFinished(const BattleID & battleID)
  387. {
  388. for(auto side : { BattleSide::ATTACKER, BattleSide::DEFENDER })
  389. {
  390. if(battleCallbacks.count(gameState().getBattle(battleID)->getSide(side).color))
  391. battleCallbacks[gameState().getBattle(battleID)->getSide(side).color]->onBattleEnded(battleID);
  392. }
  393. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  394. battleCallbacks[PlayerColor::SPECTATOR]->onBattleEnded(battleID);
  395. }
  396. void CClient::startPlayerBattleAction(const BattleID & battleID, PlayerColor color)
  397. {
  398. if (battleints.count(color) == 0)
  399. return; // not our combat in MP
  400. auto battleint = battleints.at(color);
  401. if (!battleint->human)
  402. {
  403. // we want to avoid locking gamestate and causing UI to freeze while AI is making turn
  404. auto unlockInterface = vstd::makeUnlockGuard(ENGINE->interfaceMutex);
  405. battleint->activeStack(battleID, gameState().getBattle(battleID)->battleGetStackByID(gameState().getBattle(battleID)->activeStack, false));
  406. }
  407. else
  408. {
  409. battleint->activeStack(battleID, gameState().getBattle(battleID)->battleGetStackByID(gameState().getBattle(battleID)->activeStack, false));
  410. }
  411. }
  412. void CClient::reinitScripting()
  413. {
  414. clientEventBus = std::make_unique<events::EventBus>();
  415. #if SCRIPTING_ENABLED
  416. clientScripts.reset(new scripting::PoolImpl(this));
  417. #endif
  418. }
  419. void CClient::removeGUI() const
  420. {
  421. // CClient::endGame
  422. ENGINE->windows().clear();
  423. adventureInt.reset();
  424. logGlobal->info("Removed GUI.");
  425. GAME->setInterfaceInstance(nullptr);
  426. }
  427. #ifdef VCMI_ANDROID
  428. extern "C" JNIEXPORT jboolean JNICALL Java_eu_vcmi_vcmi_NativeMethods_tryToSaveTheGame(JNIEnv * env, jclass cls)
  429. {
  430. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  431. logGlobal->info("Received emergency save game request");
  432. if(!GAME->interface() || !GAME->interface()->cb)
  433. {
  434. logGlobal->info("... but no active player interface found!");
  435. return false;
  436. }
  437. if (!GAME->server().logicConnection)
  438. {
  439. logGlobal->info("... but no active connection found!");
  440. return false;
  441. }
  442. GAME->interface()->cb->save("Saves/_Android_Autosave");
  443. return true;
  444. }
  445. #endif
  446. void CClient::registerBattleInterface(std::shared_ptr<IBattleEventsReceiver> battleEvents, PlayerColor color)
  447. {
  448. additionalBattleInts[color].push_back(battleEvents);
  449. }
  450. void CClient::unregisterBattleInterface(std::shared_ptr<IBattleEventsReceiver> battleEvents, PlayerColor color)
  451. {
  452. additionalBattleInts[color] -= battleEvents;
  453. }