CPlayerInterface.cpp 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917
  1. /*
  2. * CPlayerInterface.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 "CPlayerInterface.h"
  12. #include <vcmi/Artifact.h>
  13. #include "Client.h"
  14. #include "CServerHandler.h"
  15. #include "HeroMovementController.h"
  16. #include "PlayerLocalState.h"
  17. #include "adventureMap/AdventureMapInterface.h"
  18. #include "adventureMap/CInGameConsole.h"
  19. #include "adventureMap/CList.h"
  20. #include "battle/BattleEffectsController.h"
  21. #include "battle/BattleFieldController.h"
  22. #include "battle/BattleInterface.h"
  23. #include "battle/BattleResultWindow.h"
  24. #include "battle/BattleWindow.h"
  25. #include "eventsSDL/InputHandler.h"
  26. #include "eventsSDL/NotificationHandler.h"
  27. #include "GameEngine.h"
  28. #include "GameInstance.h"
  29. #include "gui/CursorHandler.h"
  30. #include "gui/WindowHandler.h"
  31. #include "mainmenu/CMainMenu.h"
  32. #include "mainmenu/CHighScoreScreen.h"
  33. #include "mainmenu/CStatisticScreen.h"
  34. #include "mapView/mapHandler.h"
  35. #include "media/IMusicPlayer.h"
  36. #include "media/ISoundPlayer.h"
  37. #include "render/CAnimation.h"
  38. #include "render/IImage.h"
  39. #include "render/IRenderHandler.h"
  40. #include "render/IScreenHandler.h"
  41. #include "widgets/Buttons.h"
  42. #include "widgets/CComponent.h"
  43. #include "widgets/CGarrisonInt.h"
  44. #include "windows/CCastleInterface.h"
  45. #include "windows/CCreatureWindow.h"
  46. #include "windows/CExchangeWindow.h"
  47. #include "windows/CHeroWindow.h"
  48. #include "windows/CKingdomInterface.h"
  49. #include "windows/CMarketWindow.h"
  50. #include "windows/CPuzzleWindow.h"
  51. #include "windows/CQuestLog.h"
  52. #include "windows/CSpellWindow.h"
  53. #include "windows/CTutorialWindow.h"
  54. #include "windows/GUIClasses.h"
  55. #include "windows/InfoWindows.h"
  56. #include "windows/settings/SettingsMainWindow.h"
  57. #include "../lib/callback/CDynLibHandler.h"
  58. #include "../lib/CConfigHandler.h"
  59. #include "../lib/GameLibrary.h"
  60. #include "../lib/texts/CGeneralTextHandler.h"
  61. #include "../lib/CPlayerState.h"
  62. #include "../lib/CRandomGenerator.h"
  63. #include "../lib/CStack.h"
  64. #include "../lib/CStopWatch.h"
  65. #include "../lib/CThreadHelper.h"
  66. #include "../lib/GameConstants.h"
  67. #include "../lib/RoadHandler.h"
  68. #include "../lib/StartInfo.h"
  69. #include "../lib/TerrainHandler.h"
  70. #include "../lib/UnlockGuard.h"
  71. #include "../lib/VCMIDirs.h"
  72. #include "../lib/battle/CPlayerBattleCallback.h"
  73. #include "../lib/bonuses/Limiters.h"
  74. #include "../lib/bonuses/Propagators.h"
  75. #include "../lib/bonuses/Updaters.h"
  76. #include "../lib/callback/CCallback.h"
  77. #include "../lib/gameState/CGameState.h"
  78. #include "../lib/mapObjects/CGMarket.h"
  79. #include "../lib/mapObjects/CGTownInstance.h"
  80. #include "../lib/mapObjects/MiscObjects.h"
  81. #include "../lib/mapObjects/ObjectTemplate.h"
  82. #include "../lib/mapping/CMap.h"
  83. #include "../lib/mapping/CMapHeader.h"
  84. #include "../lib/networkPacks/PacksForClient.h"
  85. #include "../lib/networkPacks/PacksForClientBattle.h"
  86. #include "../lib/networkPacks/PacksForServer.h"
  87. #include "../lib/pathfinder/CGPathNode.h"
  88. #include "../lib/pathfinder/PathfinderCache.h"
  89. #include "../lib/pathfinder/PathfinderOptions.h"
  90. #include "../lib/serializer/CTypeList.h"
  91. #include "../lib/serializer/ESerializationVersion.h"
  92. #include "../lib/spells/CSpellHandler.h"
  93. #include "../lib/texts/TextOperations.h"
  94. #include "../lib/filesystem/Filesystem.h"
  95. #include <boost/lexical_cast.hpp>
  96. // The macro below is used to mark functions that are called by client when game state changes.
  97. // They all assume that interface mutex is locked.
  98. #define EVENT_HANDLER_CALLED_BY_CLIENT
  99. #define BATTLE_EVENT_POSSIBLE_RETURN if (GAME->interface() != this) return; if (isAutoFightOn && !battleInt) return
  100. std::shared_ptr<BattleInterface> CPlayerInterface::battleInt;
  101. CPlayerInterface::CPlayerInterface(PlayerColor Player):
  102. localState(std::make_unique<PlayerLocalState>(*this)),
  103. movementController(std::make_unique<HeroMovementController>()),
  104. artifactController(std::make_unique<ArtifactsUIController>())
  105. {
  106. logGlobal->trace("\tHuman player interface for player %s being constructed", Player.toString());
  107. GAME->setInterfaceInstance(this);
  108. playerID=Player;
  109. human=true;
  110. battleInt.reset();
  111. castleInt = nullptr;
  112. makingTurn = false;
  113. showingDialog = new ConditionalWait();
  114. cingconsole = new CInGameConsole();
  115. autosaveCount = 0;
  116. isAutoFightOn = false;
  117. isAutoFightEndBattle = false;
  118. ignoreEvents = false;
  119. hasQuickSave = checkQuickLoadingGame();
  120. }
  121. CPlayerInterface::~CPlayerInterface()
  122. {
  123. logGlobal->trace("\tHuman player interface for player %s being destructed", playerID.toString());
  124. delete showingDialog;
  125. delete cingconsole;
  126. if (GAME->interface() == this)
  127. GAME->setInterfaceInstance(nullptr);
  128. }
  129. void CPlayerInterface::initGameInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CCallback> CB)
  130. {
  131. cb = CB;
  132. env = ENV;
  133. pathfinderCache = std::make_unique<PathfinderCache>(cb.get(), PathfinderOptions(*cb));
  134. ENGINE->music().loadTerrainMusicThemes();
  135. initializeHeroTownList();
  136. adventureInt.reset(new AdventureMapInterface());
  137. }
  138. std::shared_ptr<const CPathsInfo> CPlayerInterface::getPathsInfo(const CGHeroInstance * h)
  139. {
  140. return pathfinderCache->getPathsInfo(h);
  141. }
  142. void CPlayerInterface::invalidatePaths()
  143. {
  144. pathfinderCache->invalidatePaths();
  145. }
  146. void CPlayerInterface::closeAllDialogs()
  147. {
  148. // remove all active dialogs that do not expect query answer
  149. while(true)
  150. {
  151. auto adventureWindow = ENGINE->windows().topWindow<AdventureMapInterface>();
  152. auto settingsWindow = ENGINE->windows().topWindow<SettingsMainWindow>();
  153. auto infoWindow = ENGINE->windows().topWindow<CInfoWindow>();
  154. auto topWindow = ENGINE->windows().topWindow<WindowBase>();
  155. if(adventureWindow != nullptr)
  156. break;
  157. if(infoWindow && infoWindow->ID != QueryID::NONE)
  158. break;
  159. if (settingsWindow)
  160. {
  161. settingsWindow->close();
  162. continue;
  163. }
  164. if (topWindow)
  165. topWindow->close();
  166. else
  167. ENGINE->windows().popWindows(1); // does not inherits from WindowBase, e.g. settings dialog
  168. }
  169. }
  170. void CPlayerInterface::playerEndsTurn(PlayerColor player)
  171. {
  172. EVENT_HANDLER_CALLED_BY_CLIENT;
  173. if (player == playerID)
  174. {
  175. makingTurn = false;
  176. closeAllDialogs();
  177. // remove all pending dialogs that do not expect query answer
  178. vstd::erase_if(dialogs, [](const std::shared_ptr<CInfoWindow> & window){
  179. return window->ID == QueryID::NONE;
  180. });
  181. }
  182. }
  183. void CPlayerInterface::playerStartsTurn(PlayerColor player)
  184. {
  185. if(ENGINE->windows().findWindows<AdventureMapInterface>().empty())
  186. {
  187. // after map load - remove all active windows and replace them with adventure map
  188. ENGINE->windows().clear();
  189. ENGINE->windows().pushWindow(adventureInt);
  190. }
  191. EVENT_HANDLER_CALLED_BY_CLIENT;
  192. if (player != playerID && GAME->interface() == this)
  193. {
  194. waitWhileDialog();
  195. bool isHuman = cb->getStartInfo()->playerInfos.count(player) && cb->getStartInfo()->playerInfos.at(player).isControlledByHuman();
  196. if (makingTurn == false)
  197. adventureInt->onEnemyTurnStarted(player, isHuman);
  198. }
  199. }
  200. void CPlayerInterface::performAutosave()
  201. {
  202. int frequency = static_cast<int>(settings["general"]["saveFrequency"].Integer());
  203. if(frequency > 0 && cb->getDate() % frequency == 0)
  204. {
  205. bool usePrefix = settings["general"]["useSavePrefix"].Bool();
  206. std::string prefix = std::string();
  207. if(usePrefix)
  208. {
  209. prefix = settings["general"]["savePrefix"].String();
  210. if(prefix.empty())
  211. {
  212. std::string name = cb->getMapHeader()->name.toString();
  213. int txtlen = TextOperations::getUnicodeCharactersCount(name);
  214. TextOperations::trimRightUnicode(name, std::max(0, txtlen - 14));
  215. auto const & isSymbolIllegal = [&](char c) {
  216. static const std::string forbiddenChars("\\/:*?\"<>| ");
  217. bool charForbidden = forbiddenChars.find(c) != std::string::npos;
  218. bool charNonprintable = static_cast<unsigned char>(c) < static_cast<unsigned char>(' ');
  219. return charForbidden || charNonprintable;
  220. };
  221. std::replace_if(name.begin(), name.end(), isSymbolIllegal, '_' );
  222. prefix = vstd::getFormattedDateTime(cb->getStartInfo()->startTime, "%Y-%m-%d_%H-%M") + "_" + name + "/";
  223. }
  224. }
  225. autosaveCount++;
  226. int autosaveCountLimit = settings["general"]["autosaveCountLimit"].Integer();
  227. if(autosaveCountLimit > 0)
  228. {
  229. cb->save("Saves/Autosave/" + prefix + std::to_string(autosaveCount));
  230. autosaveCount %= autosaveCountLimit;
  231. }
  232. else
  233. {
  234. std::string stringifiedDate = std::to_string(cb->getDate(Date::MONTH))
  235. + std::to_string(cb->getDate(Date::WEEK))
  236. + std::to_string(cb->getDate(Date::DAY_OF_WEEK));
  237. cb->save("Saves/Autosave/" + prefix + stringifiedDate);
  238. }
  239. }
  240. }
  241. void CPlayerInterface::gamePause(bool pause)
  242. {
  243. cb->gamePause(pause);
  244. }
  245. void CPlayerInterface::yourTurn(QueryID queryID)
  246. {
  247. closeAllDialogs();
  248. CTutorialWindow::openWindowFirstTime(TutorialMode::TOUCH_ADVENTUREMAP);
  249. EVENT_HANDLER_CALLED_BY_CLIENT;
  250. int humanPlayersCount = 0;
  251. for(const auto & info : cb->getStartInfo()->playerInfos)
  252. if (info.second.isControlledByHuman())
  253. humanPlayersCount++;
  254. bool hotseatWait = humanPlayersCount > 1;
  255. GAME->setInterfaceInstance(this);
  256. NotificationHandler::notify("Your turn");
  257. if(settings["general"]["startTurnAutosave"].Bool())
  258. {
  259. performAutosave();
  260. }
  261. if (hotseatWait) //hot seat or MP message
  262. {
  263. adventureInt->onHotseatWaitStarted(playerID);
  264. makingTurn = true;
  265. std::string msg = LIBRARY->generaltexth->allTexts[13];
  266. boost::replace_first(msg, "%s", cb->getStartInfo()->playerInfos.find(playerID)->second.name);
  267. std::vector<std::shared_ptr<CComponent>> cmp;
  268. cmp.push_back(std::make_shared<CComponent>(ComponentType::FLAG, playerID));
  269. showInfoDialog(msg, cmp);
  270. }
  271. else
  272. {
  273. makingTurn = true;
  274. adventureInt->onPlayerTurnStarted(playerID);
  275. }
  276. acceptTurn(queryID, hotseatWait);
  277. }
  278. void CPlayerInterface::acceptTurn(QueryID queryID, bool hotseatWait)
  279. {
  280. if (settings["session"]["autoSkip"].Bool())
  281. {
  282. while(auto iw = ENGINE->windows().topWindow<CInfoWindow>())
  283. iw->close();
  284. }
  285. if(hotseatWait)
  286. {
  287. waitWhileDialog(); // wait for player to accept turn in hot-seat mode
  288. adventureInt->onPlayerTurnStarted(playerID);
  289. }
  290. // warn player if he has no town
  291. if (cb->howManyTowns() == 0)
  292. {
  293. auto playerColor = *cb->getPlayerID();
  294. std::vector<Component> components;
  295. components.emplace_back(ComponentType::FLAG, playerColor);
  296. MetaString text;
  297. const auto & optDaysWithoutCastle = cb->getPlayerState(playerColor)->daysWithoutCastle;
  298. if(optDaysWithoutCastle)
  299. {
  300. auto daysWithoutCastle = optDaysWithoutCastle.value();
  301. if (daysWithoutCastle < 6)
  302. {
  303. text.appendLocalString(EMetaText::ARRAY_TXT,128); //%s, you only have %d days left to capture a town or you will be banished from this land.
  304. text.replaceName(playerColor);
  305. text.replaceNumber(7 - daysWithoutCastle);
  306. }
  307. else if (daysWithoutCastle == 6)
  308. {
  309. text.appendLocalString(EMetaText::ARRAY_TXT,129); //%s, this is your last day to capture a town or you will be banished from this land.
  310. text.replaceName(playerColor);
  311. }
  312. showInfoDialogAndWait(components, text);
  313. }
  314. else
  315. logGlobal->warn("Player has no towns, but daysWithoutCastle is not set");
  316. }
  317. cb->selectionMade(0, queryID);
  318. movementController->onPlayerTurnStarted();
  319. }
  320. void CPlayerInterface::heroMoved(const TryMoveHero & details, bool verbose)
  321. {
  322. EVENT_HANDLER_CALLED_BY_CLIENT;
  323. waitWhileDialog();
  324. if(GAME->interface() != this)
  325. return;
  326. //FIXME: read once and store
  327. if(settings["session"]["spectate"].Bool() && settings["session"]["spectate-ignore-hero"].Bool())
  328. return;
  329. const CGHeroInstance * hero = cb->getHero(details.id); //object representing this hero
  330. if (!hero)
  331. return;
  332. movementController->onTryMoveHero(hero, details);
  333. }
  334. void CPlayerInterface::heroKilled(const CGHeroInstance* hero)
  335. {
  336. EVENT_HANDLER_CALLED_BY_CLIENT;
  337. LOG_TRACE_PARAMS(logGlobal, "Hero %s killed handler for player %s", hero->getNameTranslated() % playerID);
  338. // if hero is not in town garrison
  339. if (vstd::contains(localState->getWanderingHeroes(), hero))
  340. localState->removeWanderingHero(hero);
  341. adventureInt->onHeroChanged(hero);
  342. localState->erasePath(hero);
  343. }
  344. void CPlayerInterface::townRemoved(const CGTownInstance* town)
  345. {
  346. EVENT_HANDLER_CALLED_BY_CLIENT;
  347. if(town->tempOwner == playerID)
  348. {
  349. localState->removeOwnedTown(town);
  350. adventureInt->onTownChanged(town);
  351. }
  352. }
  353. void CPlayerInterface::heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start)
  354. {
  355. EVENT_HANDLER_CALLED_BY_CLIENT;
  356. if(start && visitedObj)
  357. {
  358. auto visitSound = visitedObj->getVisitSound(CRandomGenerator::getDefault());
  359. if (visitSound)
  360. ENGINE->sound().playSound(visitSound.value());
  361. }
  362. }
  363. void CPlayerInterface::heroCreated(const CGHeroInstance * hero)
  364. {
  365. EVENT_HANDLER_CALLED_BY_CLIENT;
  366. localState->addWanderingHero(hero);
  367. adventureInt->onHeroChanged(hero);
  368. if(castleInt)
  369. ENGINE->sound().playSound(soundBase::newBuilding);
  370. }
  371. void CPlayerInterface::openTownWindow(const CGTownInstance * town)
  372. {
  373. if(castleInt)
  374. castleInt->close();
  375. castleInt = nullptr;
  376. auto newCastleInt = std::make_shared<CCastleInterface>(town);
  377. ENGINE->windows().pushWindow(newCastleInt);
  378. }
  379. void CPlayerInterface::heroExperienceChanged(const CGHeroInstance * hero, si64 val)
  380. {
  381. EVENT_HANDLER_CALLED_BY_CLIENT;
  382. for(auto ctw : ENGINE->windows().findWindows<IMarketHolder>())
  383. ctw->updateExperience();
  384. }
  385. void CPlayerInterface::heroPrimarySkillChanged(const CGHeroInstance * hero, PrimarySkill which, si64 val)
  386. {
  387. EVENT_HANDLER_CALLED_BY_CLIENT;
  388. adventureInt->onHeroChanged(hero);
  389. }
  390. void CPlayerInterface::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  391. {
  392. EVENT_HANDLER_CALLED_BY_CLIENT;
  393. for (auto cuw : ENGINE->windows().findWindows<IMarketHolder>())
  394. cuw->updateSecondarySkills();
  395. localState->verifyPath(hero);
  396. adventureInt->onHeroChanged(hero);// secondary skill can change primary skill / mana limit
  397. }
  398. void CPlayerInterface::heroManaPointsChanged(const CGHeroInstance * hero)
  399. {
  400. EVENT_HANDLER_CALLED_BY_CLIENT;
  401. adventureInt->onHeroChanged(hero);
  402. if (makingTurn && hero->tempOwner == playerID)
  403. adventureInt->onHeroChanged(hero);
  404. }
  405. void CPlayerInterface::heroMovePointsChanged(const CGHeroInstance * hero)
  406. {
  407. EVENT_HANDLER_CALLED_BY_CLIENT;
  408. if (makingTurn && hero->tempOwner == playerID)
  409. adventureInt->onHeroChanged(hero);
  410. invalidatePaths();
  411. localState->verifyPath(hero);
  412. }
  413. void CPlayerInterface::receivedResource()
  414. {
  415. EVENT_HANDLER_CALLED_BY_CLIENT;
  416. for (auto mw : ENGINE->windows().findWindows<IMarketHolder>())
  417. mw->updateResources();
  418. ENGINE->windows().totalRedraw();
  419. }
  420. void CPlayerInterface::heroGotLevel(const CGHeroInstance *hero, PrimarySkill pskill, std::vector<SecondarySkill>& skills, QueryID queryID)
  421. {
  422. EVENT_HANDLER_CALLED_BY_CLIENT;
  423. waitWhileDialog();
  424. ENGINE->sound().playSound(soundBase::heroNewLevel);
  425. ENGINE->windows().createAndPushWindow<CLevelWindow>(hero, pskill, skills, [this, queryID](ui32 selection)
  426. {
  427. cb->selectionMade(selection, queryID);
  428. });
  429. }
  430. void CPlayerInterface::commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  431. {
  432. EVENT_HANDLER_CALLED_BY_CLIENT;
  433. waitWhileDialog();
  434. ENGINE->sound().playSound(soundBase::heroNewLevel);
  435. ENGINE->windows().createAndPushWindow<CStackWindow>(commander, skills, [this, queryID](ui32 selection)
  436. {
  437. cb->selectionMade(selection, queryID);
  438. });
  439. }
  440. void CPlayerInterface::heroInGarrisonChange(const CGTownInstance *town)
  441. {
  442. EVENT_HANDLER_CALLED_BY_CLIENT;
  443. if(town->getGarrisonHero()) //wandering hero moved to the garrison
  444. {
  445. // This method also gets called on hero recruitment -> garrisoned hero is already in garrison
  446. if(town->getGarrisonHero()->tempOwner == playerID && vstd::contains(localState->getWanderingHeroes(), town->getGarrisonHero()))
  447. localState->removeWanderingHero(town->getGarrisonHero());
  448. }
  449. if(town->getVisitingHero()) //hero leaves garrison
  450. {
  451. // This method also gets called on hero recruitment -> wandering heroes already contains new hero
  452. if(town->getVisitingHero()->tempOwner == playerID && !vstd::contains(localState->getWanderingHeroes(), town->getVisitingHero()))
  453. localState->addWanderingHero(town->getVisitingHero());
  454. }
  455. adventureInt->onHeroChanged(nullptr);
  456. adventureInt->onTownChanged(town);
  457. for (auto cgh : ENGINE->windows().findWindows<IGarrisonHolder>())
  458. if (cgh->holdsGarrison(town))
  459. cgh->updateGarrisons();
  460. for (auto ki : ENGINE->windows().findWindows<CKingdomInterface>())
  461. ki->townChanged(town);
  462. // Perform totalRedraw to update hero list on adventure map, if any dialogs are open
  463. ENGINE->windows().totalRedraw();
  464. }
  465. void CPlayerInterface::heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town)
  466. {
  467. EVENT_HANDLER_CALLED_BY_CLIENT;
  468. if (hero->tempOwner != playerID )
  469. return;
  470. waitWhileDialog();
  471. openTownWindow(town);
  472. }
  473. void CPlayerInterface::garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2)
  474. {
  475. std::vector<const CArmedInstance *> instances;
  476. if(auto obj = dynamic_cast<const CArmedInstance *>(cb->getObjInstance(id1)))
  477. instances.push_back(obj);
  478. if(id2 != ObjectInstanceID() && id2 != id1)
  479. {
  480. if(auto obj = dynamic_cast<const CArmedInstance *>(cb->getObjInstance(id2)))
  481. instances.push_back(obj);
  482. }
  483. garrisonsChanged(instances);
  484. }
  485. void CPlayerInterface::garrisonsChanged(std::vector<const CArmedInstance *> objs)
  486. {
  487. for (auto object : objs)
  488. {
  489. auto * hero = dynamic_cast<const CGHeroInstance*>(object);
  490. auto * town = dynamic_cast<const CGTownInstance*>(object);
  491. if (town)
  492. adventureInt->onTownChanged(town);
  493. if (hero)
  494. {
  495. localState->verifyPath(hero);
  496. adventureInt->onHeroChanged(hero);
  497. if(hero->isGarrisoned() && hero->getVisitedTown() != town)
  498. adventureInt->onTownChanged(hero->getVisitedTown());
  499. }
  500. }
  501. for (auto cgh : ENGINE->windows().findWindows<IGarrisonHolder>())
  502. if (cgh->holdsGarrisons(objs))
  503. cgh->updateGarrisons();
  504. ENGINE->windows().totalRedraw();
  505. }
  506. void CPlayerInterface::buildChanged(const CGTownInstance *town, BuildingID buildingID, int what) //what: 1 - built, 2 - demolished
  507. {
  508. EVENT_HANDLER_CALLED_BY_CLIENT;
  509. adventureInt->onTownChanged(town);
  510. if (castleInt)
  511. {
  512. castleInt->townlist->updateElement(town);
  513. if (castleInt->town == town)
  514. {
  515. switch(what)
  516. {
  517. case 1:
  518. castleInt->addBuilding(buildingID);
  519. break;
  520. case 2:
  521. castleInt->removeBuilding(buildingID);
  522. break;
  523. }
  524. }
  525. // Perform totalRedraw in order to force redraw of updated town list icon from adventure map
  526. ENGINE->windows().totalRedraw();
  527. }
  528. for (auto cgh : ENGINE->windows().findWindows<ITownHolder>())
  529. cgh->buildChanged();
  530. }
  531. void CPlayerInterface::battleStartBefore(const BattleID & battleID, const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2)
  532. {
  533. movementController->onBattleStarted();
  534. waitForAllDialogs();
  535. }
  536. void CPlayerInterface::battleStart(const BattleID & battleID, const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, BattleSide side, bool replayAllowed)
  537. {
  538. EVENT_HANDLER_CALLED_BY_CLIENT;
  539. bool useQuickCombat = settings["adventure"]["quickCombat"].Bool() || GAME->map().getMap()->battleOnly;
  540. bool forceQuickCombat = settings["adventure"]["forceQuickCombat"].Bool();
  541. if ((replayAllowed && useQuickCombat) || forceQuickCombat)
  542. {
  543. prepareAutoFightingAI(battleID, army1, army2, tile, hero1, hero2, side);
  544. }
  545. waitForAllDialogs();
  546. BATTLE_EVENT_POSSIBLE_RETURN;
  547. }
  548. void CPlayerInterface::battleUnitsChanged(const BattleID & battleID, const std::vector<UnitChanges> & units)
  549. {
  550. EVENT_HANDLER_CALLED_BY_CLIENT;
  551. BATTLE_EVENT_POSSIBLE_RETURN;
  552. for(auto & info : units)
  553. {
  554. switch(info.operation)
  555. {
  556. case UnitChanges::EOperation::RESET_STATE:
  557. {
  558. const CStack * stack = cb->getBattle(battleID)->battleGetStackByID(info.id );
  559. if(!stack)
  560. {
  561. logGlobal->error("Invalid unit ID %d", info.id);
  562. continue;
  563. }
  564. battleInt->stackReset(stack);
  565. }
  566. break;
  567. case UnitChanges::EOperation::REMOVE:
  568. battleInt->stackRemoved(info.id);
  569. break;
  570. case UnitChanges::EOperation::ADD:
  571. {
  572. const CStack * unit = cb->getBattle(battleID)->battleGetStackByID(info.id);
  573. if(!unit)
  574. {
  575. logGlobal->error("Invalid unit ID %d", info.id);
  576. continue;
  577. }
  578. battleInt->stackAdded(unit);
  579. }
  580. break;
  581. default:
  582. logGlobal->error("Unknown unit operation %d", (int)info.operation);
  583. break;
  584. }
  585. }
  586. }
  587. void CPlayerInterface::battleObstaclesChanged(const BattleID & battleID, const std::vector<ObstacleChanges> & obstacles)
  588. {
  589. EVENT_HANDLER_CALLED_BY_CLIENT;
  590. BATTLE_EVENT_POSSIBLE_RETURN;
  591. std::vector<std::shared_ptr<const CObstacleInstance>> newObstacles;
  592. std::vector<ObstacleChanges> removedObstacles;
  593. for(auto & change : obstacles)
  594. {
  595. if(change.operation == BattleChanges::EOperation::ADD)
  596. {
  597. auto instance = cb->getBattle(battleID)->battleGetObstacleByID(change.id);
  598. if(instance)
  599. newObstacles.push_back(instance);
  600. else
  601. logNetwork->error("Invalid obstacle instance %d", change.id);
  602. }
  603. if(change.operation == BattleChanges::EOperation::REMOVE)
  604. removedObstacles.push_back(change); //Obstacles are already removed, so, show animation based on json struct
  605. }
  606. if (!newObstacles.empty())
  607. battleInt->obstaclePlaced(newObstacles);
  608. if (!removedObstacles.empty())
  609. battleInt->obstacleRemoved(removedObstacles);
  610. battleInt->fieldController->redrawBackgroundWithHexes();
  611. }
  612. void CPlayerInterface::battleCatapultAttacked(const BattleID & battleID, const CatapultAttack & ca)
  613. {
  614. EVENT_HANDLER_CALLED_BY_CLIENT;
  615. BATTLE_EVENT_POSSIBLE_RETURN;
  616. battleInt->stackIsCatapulting(ca);
  617. }
  618. void CPlayerInterface::battleNewRound(const BattleID & battleID) //called at the beginning of each turn, round=-1 is the tactic phase, round=0 is the first "normal" turn
  619. {
  620. EVENT_HANDLER_CALLED_BY_CLIENT;
  621. BATTLE_EVENT_POSSIBLE_RETURN;
  622. battleInt->newRound();
  623. }
  624. void CPlayerInterface::actionStarted(const BattleID & battleID, const BattleAction &action)
  625. {
  626. EVENT_HANDLER_CALLED_BY_CLIENT;
  627. BATTLE_EVENT_POSSIBLE_RETURN;
  628. battleInt->startAction(action);
  629. }
  630. void CPlayerInterface::actionFinished(const BattleID & battleID, const BattleAction &action)
  631. {
  632. EVENT_HANDLER_CALLED_BY_CLIENT;
  633. BATTLE_EVENT_POSSIBLE_RETURN;
  634. battleInt->endAction(action);
  635. }
  636. void CPlayerInterface::activeStack(const BattleID & battleID, const CStack * stack) //called when it's turn of that stack
  637. {
  638. EVENT_HANDLER_CALLED_BY_CLIENT;
  639. logGlobal->trace("Awaiting command for %s", stack->nodeName());
  640. assert(!cb->getBattle(battleID)->battleIsFinished());
  641. if (cb->getBattle(battleID)->battleIsFinished())
  642. {
  643. logGlobal->error("Received CPlayerInterface::activeStack after battle is finished!");
  644. cb->battleMakeUnitAction(battleID, BattleAction::makeDefend(stack));
  645. return ;
  646. }
  647. if (autofightingAI)
  648. {
  649. if (isAutoFightOn)
  650. {
  651. //FIXME: we want client rendering to proceed while AI is making actions
  652. // so unlock mutex while AI is busy since this might take quite a while, especially if hero has many spells
  653. auto unlockInterface = vstd::makeUnlockGuard(ENGINE->interfaceMutex);
  654. autofightingAI->activeStack(battleID, stack);
  655. return;
  656. }
  657. unregisterBattleInterface(autofightingAI);
  658. }
  659. assert(battleInt);
  660. if(!battleInt)
  661. {
  662. // probably battle is finished already
  663. cb->battleMakeUnitAction(battleID, BattleAction::makeDefend(stack));
  664. }
  665. battleInt->stackActivated(stack);
  666. }
  667. void CPlayerInterface::battleEnd(const BattleID & battleID, const BattleResult *br, QueryID queryID)
  668. {
  669. EVENT_HANDLER_CALLED_BY_CLIENT;
  670. if(isAutoFightOn || autofightingAI)
  671. {
  672. isAutoFightOn = false;
  673. unregisterBattleInterface(autofightingAI);
  674. if(!battleInt)
  675. {
  676. bool allowManualReplay = queryID != QueryID::NONE && !isAutoFightEndBattle;
  677. auto wnd = std::make_shared<BattleResultWindow>(*br, *this, allowManualReplay);
  678. if (allowManualReplay || isAutoFightEndBattle)
  679. {
  680. wnd->resultCallback = [this, queryID](ui32 selection)
  681. {
  682. cb->selectionMade(selection, queryID);
  683. };
  684. }
  685. isAutoFightEndBattle = false;
  686. ENGINE->windows().pushWindow(wnd);
  687. // #1490 - during AI turn when quick combat is on, we need to display the message and wait for user to close it.
  688. // Otherwise NewTurn causes freeze.
  689. waitWhileDialog();
  690. return;
  691. }
  692. }
  693. BATTLE_EVENT_POSSIBLE_RETURN;
  694. battleInt->battleFinished(*br, queryID);
  695. }
  696. void CPlayerInterface::battleLogMessage(const BattleID & battleID, const std::vector<MetaString> & lines)
  697. {
  698. EVENT_HANDLER_CALLED_BY_CLIENT;
  699. BATTLE_EVENT_POSSIBLE_RETURN;
  700. battleInt->displayBattleLog(lines);
  701. }
  702. void CPlayerInterface::battleStackMoved(const BattleID & battleID, const CStack * stack, const BattleHexArray & dest, int distance, bool teleport)
  703. {
  704. EVENT_HANDLER_CALLED_BY_CLIENT;
  705. BATTLE_EVENT_POSSIBLE_RETURN;
  706. battleInt->stackMoved(stack, dest, distance, teleport);
  707. }
  708. void CPlayerInterface::battleSpellCast(const BattleID & battleID, const BattleSpellCast * sc)
  709. {
  710. EVENT_HANDLER_CALLED_BY_CLIENT;
  711. BATTLE_EVENT_POSSIBLE_RETURN;
  712. battleInt->spellCast(sc);
  713. }
  714. void CPlayerInterface::battleStacksEffectsSet(const BattleID & battleID, const SetStackEffect & sse)
  715. {
  716. EVENT_HANDLER_CALLED_BY_CLIENT;
  717. BATTLE_EVENT_POSSIBLE_RETURN;
  718. battleInt->battleStacksEffectsSet(sse);
  719. }
  720. void CPlayerInterface::battleTriggerEffect(const BattleID & battleID, const BattleTriggerEffect & bte)
  721. {
  722. EVENT_HANDLER_CALLED_BY_CLIENT;
  723. BATTLE_EVENT_POSSIBLE_RETURN;
  724. battleInt->effectsController->battleTriggerEffect(bte);
  725. if(bte.effect == BonusType::MANA_DRAIN)
  726. {
  727. const CGHeroInstance * manaDrainedHero = GAME->interface()->cb->getHero(ObjectInstanceID(bte.additionalInfo));
  728. battleInt->windowObject->heroManaPointsChanged(manaDrainedHero);
  729. }
  730. }
  731. void CPlayerInterface::battleStacksAttacked(const BattleID & battleID, const std::vector<BattleStackAttacked> & bsa, bool ranged)
  732. {
  733. EVENT_HANDLER_CALLED_BY_CLIENT;
  734. BATTLE_EVENT_POSSIBLE_RETURN;
  735. std::vector<StackAttackedInfo> arg;
  736. for(auto & elem : bsa)
  737. {
  738. const CStack * defender = cb->getBattle(battleID)->battleGetStackByID(elem.stackAttacked, false);
  739. const CStack * attacker = cb->getBattle(battleID)->battleGetStackByID(elem.attackerID, false);
  740. assert(defender);
  741. StackAttackedInfo info;
  742. info.defender = defender;
  743. info.attacker = attacker;
  744. info.damageDealt = elem.damageAmount;
  745. info.amountKilled = elem.killedAmount;
  746. info.spellEffect = SpellID::NONE;
  747. info.indirectAttack = ranged;
  748. info.killed = elem.killed();
  749. info.rebirth = elem.willRebirth();
  750. info.cloneKilled = elem.cloneKilled();
  751. info.fireShield = elem.fireShield();
  752. if (elem.isSpell())
  753. info.spellEffect = elem.spellID;
  754. arg.push_back(info);
  755. }
  756. battleInt->stacksAreAttacked(arg);
  757. }
  758. void CPlayerInterface::battleAttack(const BattleID & battleID, const BattleAttack * ba)
  759. {
  760. EVENT_HANDLER_CALLED_BY_CLIENT;
  761. BATTLE_EVENT_POSSIBLE_RETURN;
  762. StackAttackInfo info;
  763. info.attacker = cb->getBattle(battleID)->battleGetStackByID(ba->stackAttacking);
  764. info.defender = nullptr;
  765. info.indirectAttack = ba->shot();
  766. info.lucky = ba->lucky();
  767. info.unlucky = ba->unlucky();
  768. info.deathBlow = ba->deathBlow();
  769. info.lifeDrain = ba->lifeDrain();
  770. info.playCustomAnimation = ba->playCustomAnimation();
  771. info.tile = ba->tile;
  772. info.spellEffect = SpellID::NONE;
  773. if (ba->spellLike())
  774. info.spellEffect = ba->spellID;
  775. for(auto & elem : ba->bsa)
  776. {
  777. if(!elem.isSecondary())
  778. {
  779. assert(info.defender == nullptr);
  780. info.defender = cb->getBattle(battleID)->battleGetStackByID(elem.stackAttacked);
  781. }
  782. else
  783. {
  784. info.secondaryDefender.push_back(cb->getBattle(battleID)->battleGetStackByID(elem.stackAttacked));
  785. }
  786. }
  787. assert(info.defender != nullptr || (info.spellEffect != SpellID::NONE && info.indirectAttack));
  788. assert(info.attacker != nullptr);
  789. battleInt->stackAttacking(info);
  790. }
  791. void CPlayerInterface::battleGateStateChanged(const BattleID & battleID, const EGateState state)
  792. {
  793. EVENT_HANDLER_CALLED_BY_CLIENT;
  794. BATTLE_EVENT_POSSIBLE_RETURN;
  795. battleInt->gateStateChanged(state);
  796. }
  797. void CPlayerInterface::yourTacticPhase(const BattleID & battleID, int distance)
  798. {
  799. EVENT_HANDLER_CALLED_BY_CLIENT;
  800. }
  801. void CPlayerInterface::showInfoDialog(EInfoWindowMode type, const std::string &text, const std::vector<Component> & components, int soundID)
  802. {
  803. EVENT_HANDLER_CALLED_BY_CLIENT;
  804. bool autoTryHover = settings["gameTweaks"]["infoBarPick"].Bool() && type == EInfoWindowMode::AUTO;
  805. auto timer = type == EInfoWindowMode::INFO ? 3000 : 4500; //Implement long info windows like in HD mod
  806. if(autoTryHover || type == EInfoWindowMode::INFO)
  807. {
  808. waitWhileDialog(); //Fix for mantis #98
  809. adventureInt->showInfoBoxMessage(components, text, timer);
  810. // abort movement, if any. Strictly speaking unnecessary, but prevents some edge cases, like movement sound on visiting Magi Hut with "show messages in status window" on
  811. movementController->requestMovementAbort();
  812. if (makingTurn && ENGINE->windows().count() > 0 && GAME->interface() == this)
  813. ENGINE->sound().playSound(static_cast<soundBase::soundID>(soundID));
  814. return;
  815. }
  816. if (settings["session"]["autoSkip"].Bool() && !ENGINE->isKeyboardShiftDown())
  817. {
  818. return;
  819. }
  820. std::vector<Component> vect = components; //I do not know currently how to avoid copy here
  821. do
  822. {
  823. std::vector<Component> sender = {vect.begin(), vect.begin() + std::min(vect.size(), static_cast<size_t>(8))};
  824. std::vector<std::shared_ptr<CComponent>> intComps;
  825. for (auto & component : sender)
  826. intComps.push_back(std::make_shared<CComponent>(component));
  827. showInfoDialog(text,intComps,soundID);
  828. vect.erase(vect.begin(), vect.begin() + std::min(vect.size(), static_cast<size_t>(8)));
  829. }
  830. while(!vect.empty());
  831. }
  832. void CPlayerInterface::showInfoDialog(const std::string & text, std::shared_ptr<CComponent> component)
  833. {
  834. std::vector<std::shared_ptr<CComponent>> intComps;
  835. intComps.push_back(component);
  836. showInfoDialog(text, intComps, soundBase::sound_todo);
  837. }
  838. void CPlayerInterface::showInfoDialog(const std::string &text, const std::vector<std::shared_ptr<CComponent>> & components, int soundID)
  839. {
  840. LOG_TRACE_PARAMS(logGlobal, "player=%s, text=%s, is GAME->interface()=%d", playerID % text % (this==GAME->interface()));
  841. waitWhileDialog();
  842. if (settings["session"]["autoSkip"].Bool() && !ENGINE->isKeyboardShiftDown())
  843. {
  844. return;
  845. }
  846. std::shared_ptr<CInfoWindow> temp = CInfoWindow::create(text, playerID, components);
  847. if ((makingTurn || (battleInt && battleInt->curInt && battleInt->curInt.get() == this)) && ENGINE->windows().count() > 0 && GAME->interface() == this)
  848. {
  849. ENGINE->sound().playSound(static_cast<soundBase::soundID>(soundID));
  850. showingDialog->setBusy();
  851. movementController->requestMovementAbort(); // interrupt movement to show dialog
  852. ENGINE->windows().pushWindow(temp);
  853. }
  854. else
  855. {
  856. dialogs.push_back(temp);
  857. }
  858. }
  859. void CPlayerInterface::showInfoDialogAndWait(std::vector<Component> & components, const MetaString & text)
  860. {
  861. EVENT_HANDLER_CALLED_BY_CLIENT;
  862. std::string str = text.toString();
  863. showInfoDialog(EInfoWindowMode::MODAL, str, components, 0);
  864. waitWhileDialog();
  865. }
  866. void CPlayerInterface::showYesNoDialog(const std::string &text, CFunctionList<void()> onYes, CFunctionList<void()> onNo, const std::vector<std::shared_ptr<CComponent>> & components)
  867. {
  868. waitWhileDialog();
  869. movementController->requestMovementAbort();
  870. GAME->interface()->showingDialog->setBusy();
  871. CInfoWindow::showYesNoDialog(text, components, onYes, onNo, playerID);
  872. }
  873. void CPlayerInterface::showBlockingDialog(const std::string &text, const std::vector<Component> &components, QueryID askID, const int soundID, bool selection, bool cancel, bool safeToAutoaccept)
  874. {
  875. EVENT_HANDLER_CALLED_BY_CLIENT;
  876. waitWhileDialog();
  877. movementController->requestMovementAbort();
  878. ENGINE->sound().playSound(static_cast<soundBase::soundID>(soundID));
  879. if (!selection && cancel) //simple yes/no dialog
  880. {
  881. if(settings["general"]["enableUiEnhancements"].Bool() && safeToAutoaccept)
  882. {
  883. cb->selectionMade(1, askID); //as in HD mod, we try to skip dialogs that server considers visual fluff which does not affect gamestate
  884. return;
  885. }
  886. std::vector<std::shared_ptr<CComponent>> intComps;
  887. for (auto & component : components)
  888. intComps.push_back(std::make_shared<CComponent>(component)); //will be deleted by close in window
  889. showYesNoDialog(text, [this, askID](){ cb->selectionMade(1, askID); }, [this, askID](){ cb->selectionMade(0, askID); }, intComps);
  890. }
  891. else if (selection)
  892. {
  893. std::vector<std::shared_ptr<CSelectableComponent>> intComps;
  894. for (auto & component : components)
  895. intComps.push_back(std::make_shared<CSelectableComponent>(component)); //will be deleted by CSelWindow::close
  896. std::vector<std::pair<AnimationPath,CFunctionList<void()> > > pom;
  897. pom.push_back({ AnimationPath::builtin("IOKAY.DEF"),0});
  898. if (cancel)
  899. {
  900. pom.push_back({AnimationPath::builtin("ICANCEL.DEF"),0});
  901. }
  902. int charperline = 35;
  903. if (pom.size() > 1)
  904. charperline = 50;
  905. ENGINE->windows().createAndPushWindow<CSelWindow>(text, playerID, charperline, intComps, pom, askID);
  906. intComps[0]->clickPressed(ENGINE->getCursorPosition());
  907. intComps[0]->clickReleased(ENGINE->getCursorPosition());
  908. }
  909. }
  910. void CPlayerInterface::showTeleportDialog(const CGHeroInstance * hero, TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  911. {
  912. EVENT_HANDLER_CALLED_BY_CLIENT;
  913. movementController->showTeleportDialog(hero, channel, exits, impassable, askID);
  914. }
  915. void CPlayerInterface::showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects)
  916. {
  917. EVENT_HANDLER_CALLED_BY_CLIENT;
  918. std::vector<ObjectInstanceID> objectGuiOrdered = objects;
  919. std::map<ObjectInstanceID, int> townOrder;
  920. auto ownedTowns = localState->getOwnedTowns();
  921. for (int i = 0; i < ownedTowns.size(); ++i)
  922. townOrder[ownedTowns[i]->id] = i;
  923. auto townComparator = [&townOrder](const ObjectInstanceID & left, const ObjectInstanceID & right){
  924. uint32_t leftIndex= townOrder.count(left) ? townOrder.at(left) : std::numeric_limits<uint32_t>::max();
  925. uint32_t rightIndex = townOrder.count(right) ? townOrder.at(right) : std::numeric_limits<uint32_t>::max();
  926. return leftIndex < rightIndex;
  927. };
  928. std::stable_sort(objectGuiOrdered.begin(), objectGuiOrdered.end(), townComparator);
  929. auto selectCallback = [this, askID](int selection)
  930. {
  931. cb->sendQueryReply(selection, askID);
  932. };
  933. auto cancelCallback = [this, askID]()
  934. {
  935. cb->sendQueryReply(std::nullopt, askID);
  936. };
  937. const std::string localTitle = title.toString();
  938. const std::string localDescription = description.toString();
  939. std::vector<int> tempList;
  940. tempList.reserve(objectGuiOrdered.size());
  941. for(const auto & item : objectGuiOrdered)
  942. tempList.push_back(item.getNum());
  943. CComponent localIconC(icon);
  944. std::shared_ptr<CIntObject> localIcon = localIconC.image;
  945. localIconC.removeChild(localIcon.get(), false);
  946. std::vector<std::shared_ptr<IImage>> images;
  947. for(const auto & obj : objectGuiOrdered)
  948. {
  949. if(!settings["general"]["enableUiEnhancements"].Bool())
  950. break;
  951. const CGTownInstance * t = dynamic_cast<const CGTownInstance *>(cb->getObj(obj));
  952. if(t)
  953. {
  954. auto image = ENGINE->renderHandler().loadImage(AnimationPath::builtin("ITPA"), t->getTown()->clientInfo.icons[t->hasFort()][false] + 2, 0, EImageBlitMode::OPAQUE);
  955. image->scaleTo(Point(35, 23), EScalingAlgorithm::NEAREST);
  956. images.push_back(image);
  957. }
  958. }
  959. auto wnd = std::make_shared<CObjectListWindow>(tempList, localIcon, localTitle, localDescription, selectCallback, 0, images);
  960. wnd->onExit = cancelCallback;
  961. wnd->onPopup = [this, objectGuiOrdered](int index) { CRClickPopup::createAndPush(cb->getObj(objectGuiOrdered[index]), ENGINE->getCursorPosition()); };
  962. wnd->onClicked = [this, objectGuiOrdered](int index) { adventureInt->centerOnObject(cb->getObj(objectGuiOrdered[index])); ENGINE->windows().totalRedraw(); };
  963. ENGINE->windows().pushWindow(wnd);
  964. }
  965. void CPlayerInterface::tileRevealed(const FowTilesType &pos)
  966. {
  967. EVENT_HANDLER_CALLED_BY_CLIENT;
  968. //FIXME: wait for dialog? Magi hut/eye would benefit from this but may break other areas
  969. adventureInt->onMapTilesChanged(pos);
  970. }
  971. void CPlayerInterface::tileHidden(const FowTilesType &pos)
  972. {
  973. EVENT_HANDLER_CALLED_BY_CLIENT;
  974. adventureInt->onMapTilesChanged(pos);
  975. }
  976. void CPlayerInterface::openHeroWindow(const CGHeroInstance *hero)
  977. {
  978. ENGINE->windows().createAndPushWindow<CHeroWindow>(hero);
  979. }
  980. void CPlayerInterface::availableCreaturesChanged( const CGDwelling *town )
  981. {
  982. EVENT_HANDLER_CALLED_BY_CLIENT;
  983. if (const CGTownInstance * townObj = dynamic_cast<const CGTownInstance*>(town))
  984. {
  985. for (auto fortScreen : ENGINE->windows().findWindows<CFortScreen>())
  986. fortScreen->creaturesChangedEventHandler();
  987. for (auto castleInterface : ENGINE->windows().findWindows<CCastleInterface>())
  988. if(castleInterface->town == town)
  989. castleInterface->creaturesChangedEventHandler();
  990. if (townObj)
  991. for (auto ki : ENGINE->windows().findWindows<CKingdomInterface>())
  992. ki->townChanged(townObj);
  993. }
  994. else if(town && ENGINE->windows().count() > 0 && (town->ID == Obj::CREATURE_GENERATOR1
  995. || town->ID == Obj::CREATURE_GENERATOR4 || town->ID == Obj::WAR_MACHINE_FACTORY))
  996. {
  997. for (auto crw : ENGINE->windows().findWindows<CRecruitmentWindow>())
  998. if (crw->dwelling == town)
  999. crw->availableCreaturesChanged();
  1000. }
  1001. }
  1002. void CPlayerInterface::heroBonusChanged( const CGHeroInstance *hero, const Bonus &bonus, bool gain )
  1003. {
  1004. EVENT_HANDLER_CALLED_BY_CLIENT;
  1005. if (bonus.type == BonusType::NONE)
  1006. return;
  1007. adventureInt->onHeroChanged(hero);
  1008. //recalculate paths because hero has lost or gained bonus influencing pathfinding
  1009. if (bonus.type == BonusType::FLYING_MOVEMENT || bonus.type == BonusType::WATER_WALKING || bonus.type == BonusType::ROUGH_TERRAIN_DISCOUNT || bonus.type == BonusType::NO_TERRAIN_PENALTY)
  1010. localState->verifyPath(hero);
  1011. }
  1012. void CPlayerInterface::moveHero( const CGHeroInstance *h, const CGPath& path )
  1013. {
  1014. LOG_TRACE(logGlobal);
  1015. if (!GAME->interface()->makingTurn)
  1016. return;
  1017. assert(h);
  1018. assert(!showingDialog->isBusy());
  1019. assert(dialogs.empty());
  1020. if (!h)
  1021. return; //can't find hero
  1022. //It shouldn't be possible to move hero with open dialog (or dialog waiting in bg)
  1023. if (showingDialog->isBusy() || !dialogs.empty())
  1024. return;
  1025. if (localState->isHeroSleeping(h))
  1026. localState->setHeroAwaken(h);
  1027. movementController->requestMovementStart(h, path);
  1028. }
  1029. void CPlayerInterface::showGarrisonDialog( const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, QueryID queryID)
  1030. {
  1031. EVENT_HANDLER_CALLED_BY_CLIENT;
  1032. auto onEnd = [this, queryID](){ cb->selectionMade(0, queryID); };
  1033. if (movementController->isHeroMovingThroughGarrison(down, up))
  1034. {
  1035. onEnd();
  1036. return;
  1037. }
  1038. waitForAllDialogs();
  1039. auto cgw = std::make_shared<CGarrisonWindow>(up, down, removableUnits);
  1040. cgw->quit->addCallback(onEnd);
  1041. ENGINE->windows().pushWindow(cgw);
  1042. }
  1043. void CPlayerInterface::requestRealized( PackageApplied *pa )
  1044. {
  1045. if(pa->packType == CTypeList::getInstance().getTypeID<MoveHero>(nullptr))
  1046. movementController->onMoveHeroApplied();
  1047. if(pa->packType == CTypeList::getInstance().getTypeID<QueryReply>(nullptr))
  1048. movementController->onQueryReplyApplied();
  1049. }
  1050. void CPlayerInterface::showHeroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2)
  1051. {
  1052. heroExchangeStarted(hero1, hero2, QueryID(-1));
  1053. }
  1054. void CPlayerInterface::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  1055. {
  1056. EVENT_HANDLER_CALLED_BY_CLIENT;
  1057. ENGINE->windows().createAndPushWindow<CExchangeWindow>(hero1, hero2, query);
  1058. }
  1059. void CPlayerInterface::beforeObjectPropertyChanged(const SetObjectProperty * sop)
  1060. {
  1061. if (sop->what == ObjProperty::OWNER)
  1062. {
  1063. const CGObjectInstance * obj = cb->getObj(sop->id);
  1064. if(obj->ID == Obj::TOWN)
  1065. {
  1066. auto town = static_cast<const CGTownInstance *>(obj);
  1067. if(obj->tempOwner == playerID)
  1068. {
  1069. localState->removeOwnedTown(town);
  1070. adventureInt->onTownChanged(town);
  1071. }
  1072. }
  1073. }
  1074. }
  1075. void CPlayerInterface::objectPropertyChanged(const SetObjectProperty * sop)
  1076. {
  1077. EVENT_HANDLER_CALLED_BY_CLIENT;
  1078. if (sop->what == ObjProperty::OWNER)
  1079. {
  1080. const CGObjectInstance * obj = cb->getObj(sop->id);
  1081. if(obj->ID == Obj::TOWN)
  1082. {
  1083. auto town = static_cast<const CGTownInstance *>(obj);
  1084. if(obj->tempOwner == playerID)
  1085. {
  1086. localState->addOwnedTown(town);
  1087. adventureInt->onTownChanged(town);
  1088. }
  1089. }
  1090. //redraw minimap if owner changed
  1091. std::set<int3> pos = obj->getBlockedPos();
  1092. FowTilesType upos(pos.begin(), pos.end());
  1093. adventureInt->onMapTilesChanged(upos);
  1094. assert(cb->getTownsInfo().size() == localState->getOwnedTowns().size());
  1095. }
  1096. }
  1097. void CPlayerInterface::initializeHeroTownList()
  1098. {
  1099. if(localState->getWanderingHeroes().empty())
  1100. {
  1101. for(auto & hero : cb->getHeroesInfo())
  1102. {
  1103. if(!hero->isGarrisoned())
  1104. localState->addWanderingHero(hero);
  1105. }
  1106. }
  1107. if(localState->getOwnedTowns().empty())
  1108. {
  1109. for(auto & town : cb->getTownsInfo())
  1110. localState->addOwnedTown(town);
  1111. }
  1112. localState->deserialize(*cb->getPlayerState(playerID)->playerLocalSettings);
  1113. if(adventureInt)
  1114. adventureInt->onHeroChanged(nullptr);
  1115. }
  1116. void CPlayerInterface::showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level, QueryID queryID)
  1117. {
  1118. EVENT_HANDLER_CALLED_BY_CLIENT;
  1119. waitWhileDialog();
  1120. auto recruitCb = [this, dwelling, dst](CreatureID id, int count)
  1121. {
  1122. cb->recruitCreatures(dwelling, dst, id, count, -1);
  1123. };
  1124. auto closeCb = [this, queryID]()
  1125. {
  1126. cb->selectionMade(0, queryID);
  1127. };
  1128. ENGINE->windows().createAndPushWindow<CRecruitmentWindow>(dwelling, level, dst, recruitCb, closeCb);
  1129. }
  1130. void CPlayerInterface::waitWhileDialog()
  1131. {
  1132. if (ENGINE->amIGuiThread())
  1133. {
  1134. logGlobal->warn("Cannot wait for dialogs in gui thread (deadlock risk)!");
  1135. return;
  1136. }
  1137. auto unlockInterface = vstd::makeUnlockGuard(ENGINE->interfaceMutex);
  1138. showingDialog->waitWhileBusy();
  1139. }
  1140. void CPlayerInterface::showShipyardDialog(const IShipyard *obj)
  1141. {
  1142. EVENT_HANDLER_CALLED_BY_CLIENT;
  1143. auto state = obj->shipyardStatus();
  1144. TResources cost;
  1145. obj->getBoatCost(cost);
  1146. ENGINE->windows().createAndPushWindow<CShipyardWindow>(cost, state, obj->getBoatType(), [this, obj](){ cb->buildBoat(obj); });
  1147. }
  1148. void CPlayerInterface::newObject( const CGObjectInstance * obj )
  1149. {
  1150. EVENT_HANDLER_CALLED_BY_CLIENT;
  1151. //we might have built a boat in shipyard in opened town screen
  1152. if (obj->ID == Obj::BOAT
  1153. && GAME->interface()->castleInt
  1154. && obj->visitablePos() == GAME->interface()->castleInt->town->bestLocation())
  1155. {
  1156. GAME->interface()->castleInt->addBuilding(BuildingID::SHIP);
  1157. }
  1158. }
  1159. void CPlayerInterface::centerView (int3 pos, int focusTime)
  1160. {
  1161. EVENT_HANDLER_CALLED_BY_CLIENT;
  1162. waitWhileDialog();
  1163. ENGINE->cursor().hide();
  1164. adventureInt->centerOnTile(pos);
  1165. if (focusTime)
  1166. {
  1167. ENGINE->windows().totalRedraw();
  1168. {
  1169. IgnoreEvents ignore(*this);
  1170. auto unlockInterface = vstd::makeUnlockGuard(ENGINE->interfaceMutex);
  1171. std::this_thread::sleep_for(std::chrono::milliseconds(focusTime));
  1172. }
  1173. }
  1174. ENGINE->cursor().show();
  1175. }
  1176. void CPlayerInterface::objectRemoved(const CGObjectInstance * obj, const PlayerColor & initiator)
  1177. {
  1178. EVENT_HANDLER_CALLED_BY_CLIENT;
  1179. if(playerID == initiator)
  1180. {
  1181. auto removalSound = obj->getRemovalSound(CRandomGenerator::getDefault());
  1182. if (removalSound)
  1183. {
  1184. waitWhileDialog();
  1185. ENGINE->sound().playSound(removalSound.value());
  1186. }
  1187. }
  1188. GAME->map().waitForOngoingAnimations();
  1189. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  1190. {
  1191. const CGHeroInstance * h = static_cast<const CGHeroInstance *>(obj);
  1192. heroKilled(h);
  1193. }
  1194. if(obj->ID == Obj::TOWN && obj->tempOwner == playerID)
  1195. {
  1196. const CGTownInstance * t = static_cast<const CGTownInstance *>(obj);
  1197. townRemoved(t);
  1198. }
  1199. ENGINE->fakeMouseMove();
  1200. }
  1201. void CPlayerInterface::objectRemovedAfter()
  1202. {
  1203. EVENT_HANDLER_CALLED_BY_CLIENT;
  1204. adventureInt->onMapTilesChanged(boost::none);
  1205. // visiting or garrisoned hero removed - update window
  1206. if (castleInt)
  1207. castleInt->updateGarrisons();
  1208. for (auto ki : ENGINE->windows().findWindows<CKingdomInterface>())
  1209. ki->heroRemoved();
  1210. }
  1211. void CPlayerInterface::playerBlocked(int reason, bool start)
  1212. {
  1213. if(reason == PlayerBlocked::EReason::UPCOMING_BATTLE)
  1214. {
  1215. if(GAME->server().howManyPlayerInterfaces() > 1 && GAME->interface() != this && GAME->interface()->makingTurn == false && !GAME->map().getMap()->battleOnly)
  1216. {
  1217. //one of our players who isn't last in order got attacked not by our another player (happens for example in hotseat mode)
  1218. GAME->setInterfaceInstance(this);
  1219. adventureInt->onCurrentPlayerChanged(playerID);
  1220. std::string msg = LIBRARY->generaltexth->translate("vcmi.adventureMap.playerAttacked");
  1221. boost::replace_first(msg, "%s", cb->getStartInfo()->playerInfos.find(playerID)->second.name);
  1222. std::vector<std::shared_ptr<CComponent>> cmp;
  1223. cmp.push_back(std::make_shared<CComponent>(ComponentType::FLAG, playerID));
  1224. makingTurn = true; //workaround for stiff showInfoDialog implementation
  1225. showInfoDialog(msg, cmp);
  1226. waitWhileDialog();
  1227. makingTurn = false;
  1228. }
  1229. }
  1230. }
  1231. void CPlayerInterface::update()
  1232. {
  1233. //if there are any waiting dialogs, show them
  1234. if (makingTurn && !dialogs.empty() && !showingDialog->isBusy())
  1235. {
  1236. showingDialog->setBusy();
  1237. ENGINE->windows().pushWindow(dialogs.front());
  1238. dialogs.pop_front();
  1239. }
  1240. }
  1241. void CPlayerInterface::endNetwork()
  1242. {
  1243. showingDialog->requestTermination();
  1244. }
  1245. int CPlayerInterface::getLastIndex( std::string namePrefix)
  1246. {
  1247. using namespace boost::filesystem;
  1248. using namespace boost::algorithm;
  1249. path gamesDir = VCMIDirs::get().userSavePath();
  1250. std::map<std::time_t, int> dates; //save number => datestamp
  1251. const directory_iterator enddir;
  1252. if (!exists(gamesDir))
  1253. create_directory(gamesDir);
  1254. else
  1255. for (directory_iterator dir(gamesDir); dir != enddir; ++dir)
  1256. {
  1257. if (is_regular_file(dir->status()))
  1258. {
  1259. std::string name = dir->path().filename().string();
  1260. if (starts_with(name, namePrefix) && ends_with(name, ".vcgm1"))
  1261. {
  1262. char nr = name[namePrefix.size()];
  1263. if (std::isdigit(nr))
  1264. dates[last_write_time(dir->path())] = boost::lexical_cast<int>(nr);
  1265. }
  1266. }
  1267. }
  1268. if (!dates.empty())
  1269. return (--dates.end())->second; //return latest file number
  1270. return 0;
  1271. }
  1272. void CPlayerInterface::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult )
  1273. {
  1274. EVENT_HANDLER_CALLED_BY_CLIENT;
  1275. if (player == playerID)
  1276. {
  1277. if (victoryLossCheckResult.loss())
  1278. showInfoDialog(LIBRARY->generaltexth->allTexts[95]);
  1279. auto previousInterface = GAME->interface(); //without multiple player interfaces some of lines below are useless, but for hotseat we wanna swap player interface temporarily
  1280. GAME->setInterfaceInstance(this); //this is needed for dialog to show and avoid freeze, dialog showing logic should be reworked someday
  1281. if(!makingTurn)
  1282. {
  1283. makingTurn = true; //also needed for dialog to show with current implementation
  1284. waitForAllDialogs();
  1285. makingTurn = false;
  1286. }
  1287. else
  1288. waitForAllDialogs();
  1289. GAME->setInterfaceInstance(previousInterface);
  1290. }
  1291. }
  1292. void CPlayerInterface::playerBonusChanged( const Bonus &bonus, bool gain )
  1293. {
  1294. EVENT_HANDLER_CALLED_BY_CLIENT;
  1295. }
  1296. void CPlayerInterface::showPuzzleMap()
  1297. {
  1298. EVENT_HANDLER_CALLED_BY_CLIENT;
  1299. waitWhileDialog();
  1300. //TODO: interface should not know the real position of Grail...
  1301. double ratio = 0;
  1302. int3 grailPos = cb->getGrailPos(&ratio);
  1303. ENGINE->windows().createAndPushWindow<CPuzzleWindow>(grailPos, ratio);
  1304. }
  1305. void CPlayerInterface::viewWorldMap()
  1306. {
  1307. adventureInt->openWorldView();
  1308. }
  1309. void CPlayerInterface::advmapSpellCast(const CGHeroInstance * caster, SpellID spellID)
  1310. {
  1311. EVENT_HANDLER_CALLED_BY_CLIENT;
  1312. if(ENGINE->windows().topWindow<CSpellWindow>())
  1313. ENGINE->windows().popWindows(1);
  1314. auto castSoundPath = spellID.toSpell()->getCastSound();
  1315. if(!castSoundPath.empty())
  1316. ENGINE->sound().playSound(castSoundPath);
  1317. }
  1318. void CPlayerInterface::tryDigging(const CGHeroInstance * h)
  1319. {
  1320. int msgToShow = -1;
  1321. const auto diggingStatus = h->diggingStatus();
  1322. switch(diggingStatus)
  1323. {
  1324. case EDiggingStatus::CAN_DIG:
  1325. break;
  1326. case EDiggingStatus::LACK_OF_MOVEMENT:
  1327. msgToShow = 56; //"Digging for artifacts requires a whole day, try again tomorrow."
  1328. break;
  1329. case EDiggingStatus::TILE_OCCUPIED:
  1330. msgToShow = 97; //Try searching on clear ground.
  1331. break;
  1332. case EDiggingStatus::WRONG_TERRAIN:
  1333. msgToShow = 60; ////Try looking on land!
  1334. break;
  1335. case EDiggingStatus::BACKPACK_IS_FULL:
  1336. msgToShow = 247; //Searching for the Grail is fruitless...
  1337. break;
  1338. default:
  1339. assert(0);
  1340. }
  1341. if(msgToShow < 0)
  1342. cb->dig(h);
  1343. else
  1344. showInfoDialog(LIBRARY->generaltexth->allTexts[msgToShow]);
  1345. }
  1346. void CPlayerInterface::battleNewRoundFirst(const BattleID & battleID)
  1347. {
  1348. EVENT_HANDLER_CALLED_BY_CLIENT;
  1349. BATTLE_EVENT_POSSIBLE_RETURN;
  1350. battleInt->newRoundFirst();
  1351. }
  1352. void CPlayerInterface::showMarketWindow(const IMarket * market, const CGHeroInstance * visitor, QueryID queryID)
  1353. {
  1354. EVENT_HANDLER_CALLED_BY_CLIENT;
  1355. auto onWindowClosed = [this, queryID](){
  1356. cb->selectionMade(0, queryID);
  1357. };
  1358. if(market->allowsTrade(EMarketMode::ARTIFACT_EXP) && visitor->getAlignment() != EAlignment::EVIL)
  1359. ENGINE->windows().createAndPushWindow<CMarketWindow>(market, visitor, onWindowClosed, EMarketMode::ARTIFACT_EXP);
  1360. else if(market->allowsTrade(EMarketMode::CREATURE_EXP) && visitor->getAlignment() != EAlignment::GOOD)
  1361. ENGINE->windows().createAndPushWindow<CMarketWindow>(market, visitor, onWindowClosed, EMarketMode::CREATURE_EXP);
  1362. else if(market->allowsTrade(EMarketMode::CREATURE_UNDEAD))
  1363. ENGINE->windows().createAndPushWindow<CTransformerWindow>(market, visitor, onWindowClosed);
  1364. else if (!market->availableModes().empty())
  1365. for(auto mode = EMarketMode::RESOURCE_RESOURCE; mode != EMarketMode::MARKET_AFTER_LAST_PLACEHOLDER; mode = vstd::next(mode, 1))
  1366. {
  1367. if(vstd::contains(market->availableModes(), mode))
  1368. {
  1369. ENGINE->windows().createAndPushWindow<CMarketWindow>(market, visitor, onWindowClosed, mode);
  1370. break;
  1371. }
  1372. }
  1373. else
  1374. onWindowClosed();
  1375. }
  1376. void CPlayerInterface::showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor, QueryID queryID)
  1377. {
  1378. EVENT_HANDLER_CALLED_BY_CLIENT;
  1379. auto onWindowClosed = [this, queryID](){
  1380. cb->selectionMade(0, queryID);
  1381. };
  1382. ENGINE->windows().createAndPushWindow<CUniversityWindow>(visitor, BuildingID::NONE, market, onWindowClosed);
  1383. }
  1384. void CPlayerInterface::showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor)
  1385. {
  1386. EVENT_HANDLER_CALLED_BY_CLIENT;
  1387. ENGINE->windows().createAndPushWindow<CHillFortWindow>(visitor, object);
  1388. }
  1389. void CPlayerInterface::availableArtifactsChanged(const CGBlackMarket * bm)
  1390. {
  1391. EVENT_HANDLER_CALLED_BY_CLIENT;
  1392. for (auto cmw : ENGINE->windows().findWindows<IMarketHolder>())
  1393. cmw->updateArtifacts();
  1394. }
  1395. void CPlayerInterface::showTavernWindow(const CGObjectInstance * object, const CGHeroInstance * visitor, QueryID queryID)
  1396. {
  1397. EVENT_HANDLER_CALLED_BY_CLIENT;
  1398. auto onWindowClosed = [this, queryID](){
  1399. if (queryID != QueryID::NONE)
  1400. cb->selectionMade(0, queryID);
  1401. };
  1402. ENGINE->windows().createAndPushWindow<CTavernWindow>(object, onWindowClosed);
  1403. }
  1404. void CPlayerInterface::showThievesGuildWindow (const CGObjectInstance * obj)
  1405. {
  1406. EVENT_HANDLER_CALLED_BY_CLIENT;
  1407. ENGINE->windows().createAndPushWindow<CThievesGuildWindow>(obj);
  1408. }
  1409. void CPlayerInterface::showQuestLog()
  1410. {
  1411. EVENT_HANDLER_CALLED_BY_CLIENT;
  1412. ENGINE->windows().createAndPushWindow<CQuestLog>(GAME->interface()->cb->getMyQuests());
  1413. }
  1414. void CPlayerInterface::showShipyardDialogOrProblemPopup(const IShipyard *obj)
  1415. {
  1416. if (obj->shipyardStatus() != IBoatGenerator::GOOD)
  1417. {
  1418. MetaString txt;
  1419. obj->getProblemText(txt);
  1420. showInfoDialog(txt.toString());
  1421. }
  1422. else
  1423. showShipyardDialog(obj);
  1424. }
  1425. void CPlayerInterface::askToAssembleArtifact(const ArtifactLocation &al)
  1426. {
  1427. artifactController->askToAssemble(al, true, true);
  1428. }
  1429. void CPlayerInterface::artifactPut(const ArtifactLocation &al)
  1430. {
  1431. EVENT_HANDLER_CALLED_BY_CLIENT;
  1432. adventureInt->onHeroChanged(cb->getHero(al.artHolder));
  1433. }
  1434. void CPlayerInterface::artifactRemoved(const ArtifactLocation &al)
  1435. {
  1436. EVENT_HANDLER_CALLED_BY_CLIENT;
  1437. adventureInt->onHeroChanged(cb->getHero(al.artHolder));
  1438. artifactController->artifactRemoved();
  1439. }
  1440. void CPlayerInterface::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  1441. {
  1442. EVENT_HANDLER_CALLED_BY_CLIENT;
  1443. adventureInt->onHeroChanged(cb->getHero(dst.artHolder));
  1444. artifactController->artifactMoved();
  1445. }
  1446. void CPlayerInterface::bulkArtMovementStart(size_t totalNumOfArts, size_t possibleAssemblyNumOfArts)
  1447. {
  1448. artifactController->bulkArtMovementStart(totalNumOfArts, possibleAssemblyNumOfArts);
  1449. }
  1450. void CPlayerInterface::artifactAssembled(const ArtifactLocation &al)
  1451. {
  1452. EVENT_HANDLER_CALLED_BY_CLIENT;
  1453. adventureInt->onHeroChanged(cb->getHero(al.artHolder));
  1454. artifactController->artifactAssembled();
  1455. }
  1456. void CPlayerInterface::artifactDisassembled(const ArtifactLocation &al)
  1457. {
  1458. EVENT_HANDLER_CALLED_BY_CLIENT;
  1459. adventureInt->onHeroChanged(cb->getHero(al.artHolder));
  1460. artifactController->artifactDisassembled();
  1461. }
  1462. void CPlayerInterface::waitForAllDialogs()
  1463. {
  1464. if (!makingTurn)
  1465. return;
  1466. while(!dialogs.empty())
  1467. {
  1468. auto unlockInterface = vstd::makeUnlockGuard(ENGINE->interfaceMutex);
  1469. std::this_thread::sleep_for(std::chrono::milliseconds(5));
  1470. }
  1471. waitWhileDialog();
  1472. }
  1473. void CPlayerInterface::proposeLoadingGame()
  1474. {
  1475. showYesNoDialog(
  1476. LIBRARY->generaltexth->allTexts[68],
  1477. []()
  1478. {
  1479. GAME->server().endGameplay();
  1480. GAME->mainmenu()->menu->switchToTab("load");
  1481. },
  1482. nullptr
  1483. );
  1484. }
  1485. void CPlayerInterface::quickSaveGame()
  1486. {
  1487. // notify player about saving
  1488. MetaString txt;
  1489. txt.appendTextID("vcmi.adventureMap.savingQuickSave");
  1490. txt.replaceTextID(QUICKSAVE_PATH);
  1491. GAME->server().getGameChat().sendMessageGameplay(txt.toString());
  1492. GAME->interface()->cb->save(QUICKSAVE_PATH);
  1493. hasQuickSave = true;
  1494. if(adventureInt)
  1495. adventureInt->updateActiveState();
  1496. }
  1497. bool CPlayerInterface::checkQuickLoadingGame(bool verbose)
  1498. {
  1499. if(!CResourceHandler::get("local")->existsResource(ResourcePath(QUICKSAVE_PATH, EResType::SAVEGAME)))
  1500. {
  1501. if(verbose)
  1502. logGlobal->error("No quicksave file found at %s", QUICKSAVE_PATH);
  1503. else
  1504. logGlobal->trace("No quicksave file found at %s", QUICKSAVE_PATH);
  1505. hasQuickSave = false;
  1506. if(cb && adventureInt)
  1507. adventureInt->updateActiveState();
  1508. return false;
  1509. }
  1510. auto error = GAME->server().canQuickLoadGame(QUICKSAVE_PATH);
  1511. if(error)
  1512. {
  1513. if(verbose)
  1514. logGlobal->error("Cannot quick load game at %s: %s", QUICKSAVE_PATH, *error);
  1515. else
  1516. logGlobal->trace("Cannot quick load game at %s: %s", QUICKSAVE_PATH, *error);
  1517. hasQuickSave = false;
  1518. if(cb && adventureInt)
  1519. adventureInt->updateActiveState();
  1520. return false;
  1521. }
  1522. return true;
  1523. }
  1524. void CPlayerInterface::proposeQuickLoadingGame()
  1525. {
  1526. if(!checkQuickLoadingGame(true))
  1527. return;
  1528. auto onYes = [this]() -> void
  1529. {
  1530. GAME->server().quickLoadGame(QUICKSAVE_PATH);
  1531. };
  1532. GAME->interface()->showYesNoDialog(LIBRARY->generaltexth->translate("vcmi.adventureMap.confirmQuickLoadGame"), onYes, nullptr);
  1533. }
  1534. bool CPlayerInterface::capturedAllEvents()
  1535. {
  1536. if(movementController->isHeroMoving())
  1537. {
  1538. //just inform that we are capturing events. they will be processed by heroMoved() in client thread.
  1539. return true;
  1540. }
  1541. bool needToLockAdventureMap = adventureInt && adventureInt->isActive() && GAME->map().hasOngoingAnimations();
  1542. bool quickCombatOngoing = isAutoFightOn && !battleInt;
  1543. if (ignoreEvents || needToLockAdventureMap || quickCombatOngoing )
  1544. {
  1545. ENGINE->input().ignoreEventsUntilInput();
  1546. return true;
  1547. }
  1548. return false;
  1549. }
  1550. void CPlayerInterface::prepareAutoFightingAI(const BattleID &bid, const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, BattleSide side)
  1551. {
  1552. autofightingAI = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
  1553. AutocombatPreferences autocombatPreferences = AutocombatPreferences();
  1554. autocombatPreferences.enableSpellsUsage = settings["battle"]["enableAutocombatSpells"].Bool();
  1555. autofightingAI->initBattleInterface(env, cb, autocombatPreferences);
  1556. autofightingAI->battleStart(bid, army1, army2, tile, hero1, hero2, side, false);
  1557. isAutoFightOn = true;
  1558. registerBattleInterface(autofightingAI);
  1559. }
  1560. void CPlayerInterface::showWorldViewEx(const std::vector<ObjectPosInfo>& objectPositions, bool showTerrain)
  1561. {
  1562. EVENT_HANDLER_CALLED_BY_CLIENT;
  1563. adventureInt->openWorldView(objectPositions, showTerrain );
  1564. }
  1565. void CPlayerInterface::setColorScheme(ColorScheme scheme)
  1566. {
  1567. ENGINE->screenHandler().setColorScheme(scheme);
  1568. }
  1569. std::optional<BattleAction> CPlayerInterface::makeSurrenderRetreatDecision(const BattleID & battleID, const BattleStateInfoForRetreat & battleState)
  1570. {
  1571. return std::nullopt;
  1572. }
  1573. void CPlayerInterface::registerBattleInterface(std::shared_ptr<CBattleGameInterface> battleEvents)
  1574. {
  1575. autofightingAI = battleEvents;
  1576. GAME->server().client->registerBattleInterface(battleEvents, playerID);
  1577. }
  1578. void CPlayerInterface::unregisterBattleInterface(std::shared_ptr<CBattleGameInterface> battleEvents)
  1579. {
  1580. assert(battleEvents == autofightingAI);
  1581. GAME->server().client->unregisterBattleInterface(autofightingAI, playerID);
  1582. autofightingAI.reset();
  1583. }
  1584. void CPlayerInterface::responseStatistic(StatisticDataSet & statistic)
  1585. {
  1586. ENGINE->windows().createAndPushWindow<CStatisticScreen>(statistic);
  1587. }