CPlayerInterface.cpp 55 KB

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