Client.cpp 16 KB

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