CPlayerInterface.cpp 54 KB

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