CPlayerInterface.cpp 53 KB

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