CPlayerInterface.cpp 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135
  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 "adventureMap/AdventureMapInterface.h"
  14. #include "mapView/mapHandler.h"
  15. #include "adventureMap/CList.h"
  16. #include "battle/BattleInterface.h"
  17. #include "battle/BattleEffectsController.h"
  18. #include "battle/BattleFieldController.h"
  19. #include "battle/BattleInterfaceClasses.h"
  20. #include "battle/BattleWindow.h"
  21. #include "../CCallback.h"
  22. #include "windows/CCastleInterface.h"
  23. #include "eventsSDL/InputHandler.h"
  24. #include "mainmenu/CMainMenu.h"
  25. #include "gui/CursorHandler.h"
  26. #include "windows/CKingdomInterface.h"
  27. #include "CGameInfo.h"
  28. #include "PlayerLocalState.h"
  29. #include "CMT.h"
  30. #include "windows/CHeroWindow.h"
  31. #include "windows/CCreatureWindow.h"
  32. #include "windows/CQuestLog.h"
  33. #include "windows/CPuzzleWindow.h"
  34. #include "widgets/CComponent.h"
  35. #include "widgets/Buttons.h"
  36. #include "windows/CTradeWindow.h"
  37. #include "windows/CSpellWindow.h"
  38. #include "../lib/CConfigHandler.h"
  39. #include "windows/GUIClasses.h"
  40. #include "render/CAnimation.h"
  41. #include "render/IImage.h"
  42. #include "../lib/CArtHandler.h"
  43. #include "../lib/CGeneralTextHandler.h"
  44. #include "../lib/CHeroHandler.h"
  45. #include "../lib/bonuses/CBonusSystemNode.h"
  46. #include "../lib/bonuses/Limiters.h"
  47. #include "../lib/bonuses/Updaters.h"
  48. #include "../lib/bonuses/Propagators.h"
  49. #include "../lib/serializer/CTypeList.h"
  50. #include "../lib/serializer/BinaryDeserializer.h"
  51. #include "../lib/serializer/BinarySerializer.h"
  52. #include "../lib/spells/CSpellHandler.h"
  53. #include "../lib/CTownHandler.h"
  54. #include "../lib/mapObjects/CGTownInstance.h"
  55. #include "../lib/mapObjects/MiscObjects.h"
  56. #include "../lib/mapObjects/ObjectTemplate.h"
  57. #include "../lib/pathfinder/CGPathNode.h"
  58. #include "../lib/CStack.h"
  59. #include "../lib/JsonNode.h"
  60. #include "CMusicHandler.h"
  61. #include "../lib/CondSh.h"
  62. #include "../lib/NetPacksBase.h"
  63. #include "../lib/NetPacks.h"//todo: remove
  64. #include "../lib/VCMIDirs.h"
  65. #include "../lib/CStopWatch.h"
  66. #include "../lib/StartInfo.h"
  67. #include "../lib/CPlayerState.h"
  68. #include "../lib/GameConstants.h"
  69. #include "gui/CGuiHandler.h"
  70. #include "gui/WindowHandler.h"
  71. #include "windows/InfoWindows.h"
  72. #include "../lib/UnlockGuard.h"
  73. #include "../lib/RoadHandler.h"
  74. #include "../lib/TerrainHandler.h"
  75. #include "CServerHandler.h"
  76. // FIXME: only needed for CGameState::mutex
  77. #include "../lib/gameState/CGameState.h"
  78. #include "eventsSDL/NotificationHandler.h"
  79. #include "adventureMap/CInGameConsole.h"
  80. // The macro below is used to mark functions that are called by client when game state changes.
  81. // They all assume that CPlayerInterface::pim mutex is locked.
  82. #define EVENT_HANDLER_CALLED_BY_CLIENT
  83. // The macro marks functions that are run on a new thread by client.
  84. // They do not own any mutexes intiially.
  85. #define THREAD_CREATED_BY_CLIENT
  86. #define RETURN_IF_QUICK_COMBAT \
  87. if (isAutoFightOn && !battleInt) \
  88. return;
  89. #define BATTLE_EVENT_POSSIBLE_RETURN\
  90. if (LOCPLINT != this) \
  91. return; \
  92. RETURN_IF_QUICK_COMBAT
  93. boost::recursive_mutex * CPlayerInterface::pim = new boost::recursive_mutex;
  94. CPlayerInterface * LOCPLINT;
  95. std::shared_ptr<BattleInterface> CPlayerInterface::battleInt;
  96. enum EMoveState {STOP_MOVE, WAITING_MOVE, CONTINUE_MOVE, DURING_MOVE};
  97. CondSh<EMoveState> stillMoveHero(STOP_MOVE); //used during hero movement
  98. struct HeroObjectRetriever
  99. {
  100. const CGHeroInstance * operator()(const ConstTransitivePtr<CGHeroInstance> &h) const
  101. {
  102. return h;
  103. }
  104. const CGHeroInstance * operator()(const ConstTransitivePtr<CStackInstance> &s) const
  105. {
  106. return nullptr;
  107. }
  108. };
  109. CPlayerInterface::CPlayerInterface(PlayerColor Player):
  110. localState(std::make_unique<PlayerLocalState>(*this))
  111. {
  112. logGlobal->trace("\tHuman player interface for player %s being constructed", Player.getStr());
  113. destinationTeleport = ObjectInstanceID();
  114. destinationTeleportPos = int3(-1);
  115. GH.defActionsDef = 0;
  116. LOCPLINT = this;
  117. curAction = nullptr;
  118. playerID=Player;
  119. human=true;
  120. battleInt = nullptr;
  121. castleInt = nullptr;
  122. makingTurn = false;
  123. showingDialog = new CondSh<bool>(false);
  124. cingconsole = new CInGameConsole();
  125. GH.terminate_cond->set(false);
  126. firstCall = 1; //if loading will be overwritten in serialize
  127. autosaveCount = 0;
  128. isAutoFightOn = false;
  129. duringMovement = false;
  130. ignoreEvents = false;
  131. numOfMovedArts = 0;
  132. }
  133. CPlayerInterface::~CPlayerInterface()
  134. {
  135. logGlobal->trace("\tHuman player interface for player %s being destructed", playerID.getStr());
  136. delete showingDialog;
  137. delete cingconsole;
  138. if (LOCPLINT == this)
  139. LOCPLINT = nullptr;
  140. }
  141. void CPlayerInterface::initGameInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CCallback> CB)
  142. {
  143. cb = CB;
  144. env = ENV;
  145. CCS->musich->loadTerrainMusicThemes();
  146. initializeHeroTownList();
  147. // always recreate advmap interface to avoid possible memory-corruption bugs
  148. adventureInt.reset(new AdventureMapInterface());
  149. }
  150. void CPlayerInterface::playerStartsTurn(PlayerColor player)
  151. {
  152. EVENT_HANDLER_CALLED_BY_CLIENT;
  153. if(GH.windows().findWindows<AdventureMapInterface>().empty())
  154. {
  155. // after map load - remove all active windows and replace them with adventure map
  156. GH.windows().clear();
  157. GH.windows().pushWindow(adventureInt);
  158. }
  159. // remove all dialogs that do not expect query answer
  160. while (!GH.windows().topWindow<AdventureMapInterface>() && !GH.windows().topWindow<CInfoWindow>())
  161. GH.windows().popWindows(1);
  162. if (player != playerID && LOCPLINT == this)
  163. {
  164. waitWhileDialog();
  165. bool isHuman = cb->getStartInfo()->playerInfos.count(player) && cb->getStartInfo()->playerInfos.at(player).isControlledByHuman();
  166. adventureInt->onEnemyTurnStarted(player, isHuman);
  167. }
  168. }
  169. void CPlayerInterface::performAutosave()
  170. {
  171. std::string prefix = settings["session"]["saveprefix"].String();
  172. int frequency = static_cast<int>(settings["general"]["saveFrequency"].Integer());
  173. if(firstCall)
  174. {
  175. autosaveCount = getLastIndex(prefix + "Autosave_");
  176. if(firstCall > 0) //new game, not loaded
  177. {
  178. int index = getLastIndex(prefix + "Newgame_");
  179. index %= SAVES_COUNT;
  180. cb->save("Saves/" + prefix + "Newgame_Autosave_" + std::to_string(index + 1));
  181. }
  182. firstCall = 0;
  183. }
  184. else if(frequency > 0 && cb->getDate() % frequency == 0)
  185. {
  186. cb->save("Saves/" + prefix + "Autosave_" + std::to_string(autosaveCount++ + 1));
  187. autosaveCount %= 5;
  188. }
  189. }
  190. void CPlayerInterface::yourTurn()
  191. {
  192. EVENT_HANDLER_CALLED_BY_CLIENT;
  193. {
  194. LOCPLINT = this;
  195. GH.curInt = this;
  196. NotificationHandler::notify("Your turn");
  197. performAutosave();
  198. if (CSH->howManyPlayerInterfaces() > 1) //hot seat message
  199. {
  200. adventureInt->onHotseatWaitStarted(playerID);
  201. makingTurn = true;
  202. std::string msg = CGI->generaltexth->allTexts[13];
  203. boost::replace_first(msg, "%s", cb->getStartInfo()->playerInfos.find(playerID)->second.name);
  204. std::vector<std::shared_ptr<CComponent>> cmp;
  205. cmp.push_back(std::make_shared<CComponent>(CComponent::flag, playerID.getNum(), 0));
  206. showInfoDialog(msg, cmp);
  207. }
  208. else
  209. {
  210. makingTurn = true;
  211. adventureInt->onPlayerTurnStarted(playerID);
  212. }
  213. }
  214. acceptTurn();
  215. }
  216. void CPlayerInterface::acceptTurn()
  217. {
  218. if (settings["session"]["autoSkip"].Bool())
  219. {
  220. while(auto iw = GH.windows().topWindow<CInfoWindow>())
  221. iw->close();
  222. }
  223. if(CSH->howManyPlayerInterfaces() > 1)
  224. {
  225. waitWhileDialog(); // wait for player to accept turn in hot-seat mode
  226. adventureInt->onPlayerTurnStarted(playerID);
  227. }
  228. // warn player if he has no town
  229. if (cb->howManyTowns() == 0)
  230. {
  231. auto playerColor = *cb->getPlayerID();
  232. std::vector<Component> components;
  233. components.emplace_back(Component::EComponentType::FLAG, playerColor.getNum(), 0, 0);
  234. MetaString text;
  235. const auto & optDaysWithoutCastle = cb->getPlayerState(playerColor)->daysWithoutCastle;
  236. if(optDaysWithoutCastle)
  237. {
  238. auto daysWithoutCastle = optDaysWithoutCastle.value();
  239. if (daysWithoutCastle < 6)
  240. {
  241. 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.
  242. text.replaceLocalString(EMetaText::COLOR, playerColor.getNum());
  243. text.replaceNumber(7 - daysWithoutCastle);
  244. }
  245. else if (daysWithoutCastle == 6)
  246. {
  247. text.appendLocalString(EMetaText::ARRAY_TXT,129); //%s, this is your last day to capture a town or you will be banished from this land.
  248. text.replaceLocalString(EMetaText::COLOR, playerColor.getNum());
  249. }
  250. showInfoDialogAndWait(components, text);
  251. }
  252. else
  253. logGlobal->warn("Player has no towns, but daysWithoutCastle is not set");
  254. }
  255. }
  256. void CPlayerInterface::heroMoved(const TryMoveHero & details, bool verbose)
  257. {
  258. EVENT_HANDLER_CALLED_BY_CLIENT;
  259. waitWhileDialog();
  260. if(LOCPLINT != this)
  261. return;
  262. //FIXME: read once and store
  263. if(settings["session"]["spectate"].Bool() && settings["session"]["spectate-ignore-hero"].Bool())
  264. return;
  265. const CGHeroInstance * hero = cb->getHero(details.id); //object representing this hero
  266. if (!hero)
  267. return;
  268. if (details.result == TryMoveHero::EMBARK || details.result == TryMoveHero::DISEMBARK)
  269. {
  270. if(hero->getRemovalSound() && hero->tempOwner == playerID)
  271. CCS->soundh->playSound(hero->getRemovalSound().value());
  272. }
  273. std::unordered_set<int3> changedTiles {
  274. hero->convertToVisitablePos(details.start),
  275. hero->convertToVisitablePos(details.end)
  276. };
  277. adventureInt->onMapTilesChanged(changedTiles);
  278. adventureInt->onHeroMovementStarted(hero);
  279. bool directlyAttackingCreature = details.attackedFrom && localState->hasPath(hero) && localState->getPath(hero).endPos() == *details.attackedFrom;
  280. if(makingTurn && hero->tempOwner == playerID) //we are moving our hero - we may need to update assigned path
  281. {
  282. if(details.result == TryMoveHero::TELEPORTATION)
  283. {
  284. if(localState->hasPath(hero))
  285. {
  286. assert(localState->getPath(hero).nodes.size() >= 2);
  287. auto nodesIt = localState->getPath(hero).nodes.end() - 1;
  288. if((nodesIt)->coord == hero->convertToVisitablePos(details.start)
  289. && (nodesIt - 1)->coord == hero->convertToVisitablePos(details.end))
  290. {
  291. //path was between entrance and exit of teleport -> OK, erase node as usual
  292. localState->removeLastNode(hero);
  293. }
  294. else
  295. {
  296. //teleport was not along current path, it'll now be invalid (hero is somewhere else)
  297. localState->erasePath(hero);
  298. }
  299. }
  300. }
  301. if(hero->pos != details.end //hero didn't change tile but visit succeeded
  302. || directlyAttackingCreature) // or creature was attacked from endangering tile.
  303. {
  304. localState->erasePath(hero);
  305. }
  306. else if(localState->hasPath(hero) && hero->pos == details.end) //&& hero is moving
  307. {
  308. if(details.start != details.end) //so we don't touch path when revisiting with spacebar
  309. localState->removeLastNode(hero);
  310. }
  311. }
  312. if(details.stopMovement()) //hero failed to move
  313. {
  314. stillMoveHero.setn(STOP_MOVE);
  315. adventureInt->onHeroChanged(hero);
  316. return;
  317. }
  318. CGI->mh->waitForOngoingAnimations();
  319. //move finished
  320. adventureInt->onHeroChanged(hero);
  321. //check if user cancelled movement
  322. {
  323. if (GH.input().ignoreEventsUntilInput())
  324. stillMoveHero.setn(STOP_MOVE);
  325. }
  326. if (stillMoveHero.get() == WAITING_MOVE)
  327. stillMoveHero.setn(DURING_MOVE);
  328. // Hero attacked creature directly, set direction to face it.
  329. if (directlyAttackingCreature) {
  330. // Get direction to attacker.
  331. int3 posOffset = *details.attackedFrom - details.end + int3(2, 1, 0);
  332. static const ui8 dirLookup[3][3] = {
  333. { 1, 2, 3 },
  334. { 8, 0, 4 },
  335. { 7, 6, 5 }
  336. };
  337. // FIXME: Avoid const_cast, make moveDir mutable in some other way?
  338. const_cast<CGHeroInstance *>(hero)->moveDir = dirLookup[posOffset.y][posOffset.x];
  339. }
  340. }
  341. void CPlayerInterface::heroKilled(const CGHeroInstance* hero)
  342. {
  343. EVENT_HANDLER_CALLED_BY_CLIENT;
  344. LOG_TRACE_PARAMS(logGlobal, "Hero %s killed handler for player %s", hero->getNameTranslated() % playerID);
  345. // if hero is not in town garrison
  346. if (vstd::contains(localState->getWanderingHeroes(), hero))
  347. localState->removeWanderingHero(hero);
  348. adventureInt->onHeroChanged(hero);
  349. localState->erasePath(hero);
  350. }
  351. void CPlayerInterface::heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start)
  352. {
  353. EVENT_HANDLER_CALLED_BY_CLIENT;
  354. if(start && visitedObj)
  355. {
  356. if(visitedObj->getVisitSound())
  357. CCS->soundh->playSound(visitedObj->getVisitSound().value());
  358. }
  359. }
  360. void CPlayerInterface::heroCreated(const CGHeroInstance * hero)
  361. {
  362. EVENT_HANDLER_CALLED_BY_CLIENT;
  363. localState->addWanderingHero(hero);
  364. adventureInt->onHeroChanged(hero);
  365. }
  366. void CPlayerInterface::openTownWindow(const CGTownInstance * town)
  367. {
  368. if(castleInt)
  369. castleInt->close();
  370. castleInt = nullptr;
  371. auto newCastleInt = std::make_shared<CCastleInterface>(town);
  372. GH.windows().pushWindow(newCastleInt);
  373. }
  374. void CPlayerInterface::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  375. {
  376. EVENT_HANDLER_CALLED_BY_CLIENT;
  377. if (which == 4)
  378. {
  379. for (auto ctw : GH.windows().findWindows<CAltarWindow>())
  380. ctw->setExpToLevel();
  381. }
  382. else
  383. adventureInt->onHeroChanged(hero);
  384. }
  385. void CPlayerInterface::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  386. {
  387. EVENT_HANDLER_CALLED_BY_CLIENT;
  388. for (auto cuw : GH.windows().findWindows<CUniversityWindow>())
  389. cuw->redraw();
  390. }
  391. void CPlayerInterface::heroManaPointsChanged(const CGHeroInstance * hero)
  392. {
  393. EVENT_HANDLER_CALLED_BY_CLIENT;
  394. adventureInt->onHeroChanged(hero);
  395. if (makingTurn && hero->tempOwner == playerID)
  396. adventureInt->onHeroChanged(hero);
  397. }
  398. void CPlayerInterface::heroMovePointsChanged(const CGHeroInstance * hero)
  399. {
  400. EVENT_HANDLER_CALLED_BY_CLIENT;
  401. if (makingTurn && hero->tempOwner == playerID)
  402. adventureInt->onHeroChanged(hero);
  403. }
  404. void CPlayerInterface::receivedResource()
  405. {
  406. EVENT_HANDLER_CALLED_BY_CLIENT;
  407. for (auto mw : GH.windows().findWindows<CMarketplaceWindow>())
  408. mw->resourceChanged();
  409. GH.windows().totalRedraw();
  410. }
  411. void CPlayerInterface::heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill>& skills, QueryID queryID)
  412. {
  413. EVENT_HANDLER_CALLED_BY_CLIENT;
  414. waitWhileDialog();
  415. CCS->soundh->playSound(soundBase::heroNewLevel);
  416. GH.windows().createAndPushWindow<CLevelWindow>(hero, pskill, skills, [=](ui32 selection)
  417. {
  418. cb->selectionMade(selection, queryID);
  419. });
  420. }
  421. void CPlayerInterface::commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  422. {
  423. EVENT_HANDLER_CALLED_BY_CLIENT;
  424. waitWhileDialog();
  425. CCS->soundh->playSound(soundBase::heroNewLevel);
  426. GH.windows().createAndPushWindow<CStackWindow>(commander, skills, [=](ui32 selection)
  427. {
  428. cb->selectionMade(selection, queryID);
  429. });
  430. }
  431. void CPlayerInterface::heroInGarrisonChange(const CGTownInstance *town)
  432. {
  433. EVENT_HANDLER_CALLED_BY_CLIENT;
  434. if(town->garrisonHero) //wandering hero moved to the garrison
  435. {
  436. // This method also gets called on hero recruitment -> garrisoned hero is already in garrison
  437. if(town->garrisonHero->tempOwner == playerID && vstd::contains(localState->getWanderingHeroes(), town->garrisonHero))
  438. localState->removeWanderingHero(town->garrisonHero);
  439. }
  440. if(town->visitingHero) //hero leaves garrison
  441. {
  442. // This method also gets called on hero recruitment -> wandering heroes already contains new hero
  443. if(town->visitingHero->tempOwner == playerID && !vstd::contains(localState->getWanderingHeroes(), town->visitingHero))
  444. localState->addWanderingHero(town->visitingHero);
  445. }
  446. adventureInt->onHeroChanged(nullptr);
  447. adventureInt->onTownChanged(town);
  448. if(castleInt)
  449. {
  450. castleInt->garr->selectSlot(nullptr);
  451. castleInt->garr->setArmy(town->getUpperArmy(), 0);
  452. castleInt->garr->setArmy(town->visitingHero, 1);
  453. castleInt->garr->recreateSlots();
  454. castleInt->heroes->update();
  455. // Perform totalRedraw to update hero list on adventure map
  456. GH.windows().totalRedraw();
  457. }
  458. for (auto ki : GH.windows().findWindows<CKingdomInterface>())
  459. {
  460. ki->townChanged(town);
  461. ki->updateGarrisons();
  462. ki->redraw();
  463. }
  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 CGObjectInstance *> instances;
  476. if(auto obj = cb->getObj(id1))
  477. instances.push_back(obj);
  478. if(id2 != ObjectInstanceID() && id2 != id1)
  479. {
  480. if(auto obj = cb->getObj(id2))
  481. instances.push_back(obj);
  482. }
  483. garrisonsChanged(instances);
  484. }
  485. void CPlayerInterface::garrisonsChanged(std::vector<const CGObjectInstance *> objs)
  486. {
  487. boost::unique_lock<boost::recursive_mutex> un(*pim);
  488. for (auto object : objs)
  489. {
  490. auto * hero = dynamic_cast<const CGHeroInstance*>(object);
  491. auto * town = dynamic_cast<const CGTownInstance*>(object);
  492. if (hero)
  493. {
  494. adventureInt->onHeroChanged(hero);
  495. if(hero->inTownGarrison)
  496. {
  497. adventureInt->onTownChanged(hero->visitedTown);
  498. }
  499. }
  500. if (town)
  501. adventureInt->onTownChanged(town);
  502. }
  503. for (auto cgh : GH.windows().findWindows<CGarrisonHolder>())
  504. cgh->updateGarrisons();
  505. for (auto cmw : GH.windows().findWindows<CTradeWindow>())
  506. {
  507. if (vstd::contains(objs, cmw->hero))
  508. cmw->garrisonChanged();
  509. }
  510. GH.windows().totalRedraw();
  511. }
  512. void CPlayerInterface::buildChanged(const CGTownInstance *town, BuildingID buildingID, int what) //what: 1 - built, 2 - demolished
  513. {
  514. EVENT_HANDLER_CALLED_BY_CLIENT;
  515. adventureInt->onTownChanged(town);
  516. if (castleInt)
  517. {
  518. castleInt->townlist->updateElement(town);
  519. if (castleInt->town == town)
  520. {
  521. switch(what)
  522. {
  523. case 1:
  524. CCS->soundh->playSound(soundBase::newBuilding);
  525. castleInt->addBuilding(buildingID);
  526. break;
  527. case 2:
  528. castleInt->removeBuilding(buildingID);
  529. break;
  530. }
  531. }
  532. // Perform totalRedraw in order to force redraw of updated town list icon from adventure map
  533. GH.windows().totalRedraw();
  534. }
  535. }
  536. void CPlayerInterface::battleStartBefore(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2)
  537. {
  538. //Don't wait for dialogs when we are non-active hot-seat player
  539. if (LOCPLINT == this)
  540. waitForAllDialogs();
  541. }
  542. void CPlayerInterface::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  543. {
  544. EVENT_HANDLER_CALLED_BY_CLIENT;
  545. bool autoBattleResultRefused = (lastBattleArmies.first == army1 && lastBattleArmies.second == army2);
  546. lastBattleArmies.first = army1;
  547. lastBattleArmies.second = army2;
  548. //quick combat with neutral creatures only
  549. auto * army2_object = dynamic_cast<const CGObjectInstance *>(army2);
  550. if((!autoBattleResultRefused && !allowBattleReplay && army2_object
  551. && army2_object->getOwner() == PlayerColor::UNFLAGGABLE
  552. && settings["adventure"]["quickCombat"].Bool())
  553. || settings["adventure"]["alwaysSkipCombat"].Bool())
  554. {
  555. autofightingAI = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
  556. autofightingAI->initBattleInterface(env, cb);
  557. autofightingAI->battleStart(army1, army2, int3(0,0,0), hero1, hero2, side);
  558. isAutoFightOn = true;
  559. cb->registerBattleInterface(autofightingAI);
  560. // Player shouldn't be able to move on adventure map if quick combat is going
  561. allowBattleReplay = true;
  562. }
  563. //Don't wait for dialogs when we are non-active hot-seat player
  564. if (LOCPLINT == this)
  565. waitForAllDialogs();
  566. BATTLE_EVENT_POSSIBLE_RETURN;
  567. }
  568. void CPlayerInterface::battleUnitsChanged(const std::vector<UnitChanges> & units)
  569. {
  570. EVENT_HANDLER_CALLED_BY_CLIENT;
  571. BATTLE_EVENT_POSSIBLE_RETURN;
  572. for(auto & info : units)
  573. {
  574. switch(info.operation)
  575. {
  576. case UnitChanges::EOperation::RESET_STATE:
  577. {
  578. const CStack * stack = cb->battleGetStackByID(info.id );
  579. if(!stack)
  580. {
  581. logGlobal->error("Invalid unit ID %d", info.id);
  582. continue;
  583. }
  584. battleInt->stackReset(stack);
  585. }
  586. break;
  587. case UnitChanges::EOperation::REMOVE:
  588. battleInt->stackRemoved(info.id);
  589. break;
  590. case UnitChanges::EOperation::ADD:
  591. {
  592. const CStack * unit = cb->battleGetStackByID(info.id);
  593. if(!unit)
  594. {
  595. logGlobal->error("Invalid unit ID %d", info.id);
  596. continue;
  597. }
  598. battleInt->stackAdded(unit);
  599. }
  600. break;
  601. default:
  602. logGlobal->error("Unknown unit operation %d", (int)info.operation);
  603. break;
  604. }
  605. }
  606. }
  607. void CPlayerInterface::battleObstaclesChanged(const std::vector<ObstacleChanges> & obstacles)
  608. {
  609. EVENT_HANDLER_CALLED_BY_CLIENT;
  610. BATTLE_EVENT_POSSIBLE_RETURN;
  611. std::vector<std::shared_ptr<const CObstacleInstance>> newObstacles;
  612. std::vector<ObstacleChanges> removedObstacles;
  613. for(auto & change : obstacles)
  614. {
  615. if(change.operation == BattleChanges::EOperation::ADD)
  616. {
  617. auto instance = cb->battleGetObstacleByID(change.id);
  618. if(instance)
  619. newObstacles.push_back(instance);
  620. else
  621. logNetwork->error("Invalid obstacle instance %d", change.id);
  622. }
  623. if(change.operation == BattleChanges::EOperation::REMOVE)
  624. removedObstacles.push_back(change); //Obstacles are already removed, so, show animation based on json struct
  625. }
  626. if (!newObstacles.empty())
  627. battleInt->obstaclePlaced(newObstacles);
  628. if (!removedObstacles.empty())
  629. battleInt->obstacleRemoved(removedObstacles);
  630. battleInt->fieldController->redrawBackgroundWithHexes();
  631. }
  632. void CPlayerInterface::battleCatapultAttacked(const CatapultAttack & ca)
  633. {
  634. EVENT_HANDLER_CALLED_BY_CLIENT;
  635. BATTLE_EVENT_POSSIBLE_RETURN;
  636. battleInt->stackIsCatapulting(ca);
  637. }
  638. void CPlayerInterface::battleNewRound(int round) //called at the beginning of each turn, round=-1 is the tactic phase, round=0 is the first "normal" turn
  639. {
  640. EVENT_HANDLER_CALLED_BY_CLIENT;
  641. BATTLE_EVENT_POSSIBLE_RETURN;
  642. battleInt->newRound(round);
  643. }
  644. void CPlayerInterface::actionStarted(const BattleAction &action)
  645. {
  646. EVENT_HANDLER_CALLED_BY_CLIENT;
  647. BATTLE_EVENT_POSSIBLE_RETURN;
  648. curAction = new BattleAction(action);
  649. battleInt->startAction(curAction);
  650. }
  651. void CPlayerInterface::actionFinished(const BattleAction &action)
  652. {
  653. EVENT_HANDLER_CALLED_BY_CLIENT;
  654. BATTLE_EVENT_POSSIBLE_RETURN;
  655. battleInt->endAction(curAction);
  656. delete curAction;
  657. curAction = nullptr;
  658. }
  659. BattleAction CPlayerInterface::activeStack(const CStack * stack) //called when it's turn of that stack
  660. {
  661. THREAD_CREATED_BY_CLIENT;
  662. logGlobal->trace("Awaiting command for %s", stack->nodeName());
  663. auto stackId = stack->unitId();
  664. auto stackName = stack->nodeName();
  665. assert(!cb->battleIsFinished());
  666. if (cb->battleIsFinished())
  667. {
  668. logGlobal->error("Received CPlayerInterface::activeStack after battle is finished!");
  669. return BattleAction::makeDefend(stack);
  670. }
  671. if (autofightingAI)
  672. {
  673. if (isAutoFightOn)
  674. {
  675. auto ret = autofightingAI->activeStack(stack);
  676. if(cb->battleIsFinished())
  677. {
  678. return BattleAction::makeDefend(stack); // battle finished with spellcast
  679. }
  680. if (isAutoFightOn)
  681. {
  682. return ret;
  683. }
  684. }
  685. cb->unregisterBattleInterface(autofightingAI);
  686. autofightingAI.reset();
  687. }
  688. assert(battleInt);
  689. if(!battleInt)
  690. {
  691. return BattleAction::makeDefend(stack); // probably battle is finished already
  692. }
  693. if(BattleInterface::givenCommand.get())
  694. {
  695. logGlobal->error("Command buffer must be clean! (we don't want to use old command)");
  696. vstd::clear_pointer(BattleInterface::givenCommand.data);
  697. }
  698. {
  699. boost::unique_lock<boost::recursive_mutex> un(*pim);
  700. battleInt->stackActivated(stack);
  701. //Regeneration & mana drain go there
  702. }
  703. //wait till BattleInterface sets its command
  704. boost::unique_lock<boost::mutex> lock(BattleInterface::givenCommand.mx);
  705. while(!BattleInterface::givenCommand.data)
  706. {
  707. BattleInterface::givenCommand.cond.wait(lock);
  708. if (!battleInt) //battle ended while we were waiting for movement (eg. because of spell)
  709. throw boost::thread_interrupted(); //will shut the thread peacefully
  710. }
  711. //tidy up
  712. BattleAction ret = *(BattleInterface::givenCommand.data);
  713. vstd::clear_pointer(BattleInterface::givenCommand.data);
  714. if(ret.actionType == EActionType::CANCEL)
  715. {
  716. if(stackId != ret.stackNumber)
  717. logGlobal->error("Not current active stack action canceled");
  718. logGlobal->trace("Canceled command for %s", stackName);
  719. }
  720. else
  721. logGlobal->trace("Giving command for %s", stackName);
  722. return ret;
  723. }
  724. void CPlayerInterface::battleEnd(const BattleResult *br, QueryID queryID)
  725. {
  726. EVENT_HANDLER_CALLED_BY_CLIENT;
  727. if(isAutoFightOn || autofightingAI)
  728. {
  729. isAutoFightOn = false;
  730. cb->unregisterBattleInterface(autofightingAI);
  731. autofightingAI.reset();
  732. if(!battleInt)
  733. {
  734. bool allowManualReplay = allowBattleReplay && !settings["adventure"]["alwaysSkipCombat"].Bool();
  735. allowBattleReplay = false;
  736. auto wnd = std::make_shared<BattleResultWindow>(*br, *this, allowManualReplay);
  737. wnd->resultCallback = [=](ui32 selection)
  738. {
  739. cb->selectionMade(selection, queryID);
  740. };
  741. GH.windows().pushWindow(wnd);
  742. // #1490 - during AI turn when quick combat is on, we need to display the message and wait for user to close it.
  743. // Otherwise NewTurn causes freeze.
  744. waitWhileDialog();
  745. return;
  746. }
  747. }
  748. BATTLE_EVENT_POSSIBLE_RETURN;
  749. battleInt->battleFinished(*br, queryID);
  750. }
  751. void CPlayerInterface::battleLogMessage(const std::vector<MetaString> & lines)
  752. {
  753. EVENT_HANDLER_CALLED_BY_CLIENT;
  754. BATTLE_EVENT_POSSIBLE_RETURN;
  755. battleInt->displayBattleLog(lines);
  756. }
  757. void CPlayerInterface::battleStackMoved(const CStack * stack, std::vector<BattleHex> dest, int distance, bool teleport)
  758. {
  759. EVENT_HANDLER_CALLED_BY_CLIENT;
  760. BATTLE_EVENT_POSSIBLE_RETURN;
  761. battleInt->stackMoved(stack, dest, distance, teleport);
  762. }
  763. void CPlayerInterface::battleSpellCast( const BattleSpellCast *sc )
  764. {
  765. EVENT_HANDLER_CALLED_BY_CLIENT;
  766. BATTLE_EVENT_POSSIBLE_RETURN;
  767. battleInt->spellCast(sc);
  768. }
  769. void CPlayerInterface::battleStacksEffectsSet( const SetStackEffect & sse )
  770. {
  771. EVENT_HANDLER_CALLED_BY_CLIENT;
  772. BATTLE_EVENT_POSSIBLE_RETURN;
  773. battleInt->battleStacksEffectsSet(sse);
  774. }
  775. void CPlayerInterface::battleTriggerEffect (const BattleTriggerEffect & bte)
  776. {
  777. EVENT_HANDLER_CALLED_BY_CLIENT;
  778. BATTLE_EVENT_POSSIBLE_RETURN;
  779. RETURN_IF_QUICK_COMBAT;
  780. battleInt->effectsController->battleTriggerEffect(bte);
  781. }
  782. void CPlayerInterface::battleStacksAttacked(const std::vector<BattleStackAttacked> & bsa, bool ranged)
  783. {
  784. EVENT_HANDLER_CALLED_BY_CLIENT;
  785. BATTLE_EVENT_POSSIBLE_RETURN;
  786. std::vector<StackAttackedInfo> arg;
  787. for(auto & elem : bsa)
  788. {
  789. const CStack * defender = cb->battleGetStackByID(elem.stackAttacked, false);
  790. const CStack * attacker = cb->battleGetStackByID(elem.attackerID, false);
  791. assert(defender);
  792. StackAttackedInfo info;
  793. info.defender = defender;
  794. info.attacker = attacker;
  795. info.damageDealt = elem.damageAmount;
  796. info.amountKilled = elem.killedAmount;
  797. info.spellEffect = SpellID::NONE;
  798. info.indirectAttack = ranged;
  799. info.killed = elem.killed();
  800. info.rebirth = elem.willRebirth();
  801. info.cloneKilled = elem.cloneKilled();
  802. info.fireShield = elem.fireShield();
  803. if (elem.isSpell())
  804. info.spellEffect = elem.spellID;
  805. arg.push_back(info);
  806. }
  807. battleInt->stacksAreAttacked(arg);
  808. }
  809. void CPlayerInterface::battleAttack(const BattleAttack * ba)
  810. {
  811. EVENT_HANDLER_CALLED_BY_CLIENT;
  812. BATTLE_EVENT_POSSIBLE_RETURN;
  813. assert(curAction);
  814. StackAttackInfo info;
  815. info.attacker = cb->battleGetStackByID(ba->stackAttacking);
  816. info.defender = nullptr;
  817. info.indirectAttack = ba->shot();
  818. info.lucky = ba->lucky();
  819. info.unlucky = ba->unlucky();
  820. info.deathBlow = ba->deathBlow();
  821. info.lifeDrain = ba->lifeDrain();
  822. info.tile = ba->tile;
  823. info.spellEffect = SpellID::NONE;
  824. if (ba->spellLike())
  825. info.spellEffect = ba->spellID;
  826. for(auto & elem : ba->bsa)
  827. {
  828. if(!elem.isSecondary())
  829. {
  830. assert(info.defender == nullptr);
  831. info.defender = cb->battleGetStackByID(elem.stackAttacked);
  832. }
  833. else
  834. {
  835. info.secondaryDefender.push_back(cb->battleGetStackByID(elem.stackAttacked));
  836. }
  837. }
  838. assert(info.defender != nullptr);
  839. assert(info.attacker != nullptr);
  840. battleInt->stackAttacking(info);
  841. }
  842. void CPlayerInterface::battleGateStateChanged(const EGateState state)
  843. {
  844. EVENT_HANDLER_CALLED_BY_CLIENT;
  845. BATTLE_EVENT_POSSIBLE_RETURN;
  846. battleInt->gateStateChanged(state);
  847. }
  848. void CPlayerInterface::yourTacticPhase(int distance)
  849. {
  850. THREAD_CREATED_BY_CLIENT;
  851. while(battleInt && battleInt->tacticsMode)
  852. boost::this_thread::sleep(boost::posix_time::millisec(1));
  853. }
  854. void CPlayerInterface::forceEndTacticPhase()
  855. {
  856. if (battleInt)
  857. battleInt->tacticsMode = false;
  858. }
  859. void CPlayerInterface::showInfoDialog(EInfoWindowMode type, const std::string &text, const std::vector<Component> & components, int soundID)
  860. {
  861. EVENT_HANDLER_CALLED_BY_CLIENT;
  862. bool autoTryHover = settings["gameTweaks"]["infoBarPick"].Bool() && type == EInfoWindowMode::AUTO;
  863. auto timer = type == EInfoWindowMode::INFO ? 3000 : 4500; //Implement long info windows like in HD mod
  864. if(autoTryHover || type == EInfoWindowMode::INFO)
  865. {
  866. waitWhileDialog(); //Fix for mantis #98
  867. adventureInt->showInfoBoxMessage(components, text, timer);
  868. if (makingTurn && GH.windows().count() > 0 && LOCPLINT == this)
  869. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  870. return;
  871. }
  872. if (settings["session"]["autoSkip"].Bool() && !GH.isKeyboardShiftDown())
  873. {
  874. return;
  875. }
  876. std::vector<Component> vect = components; //I do not know currently how to avoid copy here
  877. do
  878. {
  879. std::vector<Component> sender = {vect.begin(), vect.begin() + std::min(vect.size(), static_cast<size_t>(8))};
  880. std::vector<std::shared_ptr<CComponent>> intComps;
  881. for (auto & component : sender)
  882. intComps.push_back(std::make_shared<CComponent>(component));
  883. showInfoDialog(text,intComps,soundID);
  884. vect.erase(vect.begin(), vect.begin() + std::min(vect.size(), static_cast<size_t>(8)));
  885. }
  886. while(!vect.empty());
  887. }
  888. void CPlayerInterface::showInfoDialog(const std::string & text, std::shared_ptr<CComponent> component)
  889. {
  890. std::vector<std::shared_ptr<CComponent>> intComps;
  891. intComps.push_back(component);
  892. showInfoDialog(text, intComps, soundBase::sound_todo);
  893. }
  894. void CPlayerInterface::showInfoDialog(const std::string &text, const std::vector<std::shared_ptr<CComponent>> & components, int soundID)
  895. {
  896. LOG_TRACE_PARAMS(logGlobal, "player=%s, text=%s, is LOCPLINT=%d", playerID % text % (this==LOCPLINT));
  897. waitWhileDialog();
  898. if (settings["session"]["autoSkip"].Bool() && !GH.isKeyboardShiftDown())
  899. {
  900. return;
  901. }
  902. std::shared_ptr<CInfoWindow> temp = CInfoWindow::create(text, playerID, components);
  903. if (makingTurn && GH.windows().count() > 0 && LOCPLINT == this)
  904. {
  905. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  906. showingDialog->set(true);
  907. stopMovement(); // interrupt movement to show dialog
  908. GH.windows().pushWindow(temp);
  909. }
  910. else
  911. {
  912. dialogs.push_back(temp);
  913. }
  914. }
  915. void CPlayerInterface::showInfoDialogAndWait(std::vector<Component> & components, const MetaString & text)
  916. {
  917. EVENT_HANDLER_CALLED_BY_CLIENT;
  918. std::string str = text.toString();
  919. showInfoDialog(EInfoWindowMode::MODAL, str, components, 0);
  920. waitWhileDialog();
  921. }
  922. void CPlayerInterface::showYesNoDialog(const std::string &text, CFunctionList<void()> onYes, CFunctionList<void()> onNo, const std::vector<std::shared_ptr<CComponent>> & components)
  923. {
  924. boost::unique_lock<boost::recursive_mutex> un(*pim);
  925. stopMovement();
  926. LOCPLINT->showingDialog->setn(true);
  927. CInfoWindow::showYesNoDialog(text, components, onYes, onNo, playerID);
  928. }
  929. void CPlayerInterface::showBlockingDialog( const std::string &text, const std::vector<Component> &components, QueryID askID, const int soundID, bool selection, bool cancel )
  930. {
  931. EVENT_HANDLER_CALLED_BY_CLIENT;
  932. waitWhileDialog();
  933. stopMovement();
  934. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  935. if (!selection && cancel) //simple yes/no dialog
  936. {
  937. std::vector<std::shared_ptr<CComponent>> intComps;
  938. for (auto & component : components)
  939. intComps.push_back(std::make_shared<CComponent>(component)); //will be deleted by close in window
  940. showYesNoDialog(text, [=](){ cb->selectionMade(1, askID); }, [=](){ cb->selectionMade(0, askID); }, intComps);
  941. }
  942. else if (selection)
  943. {
  944. std::vector<std::shared_ptr<CSelectableComponent>> intComps;
  945. for (auto & component : components)
  946. intComps.push_back(std::make_shared<CSelectableComponent>(component)); //will be deleted by CSelWindow::close
  947. std::vector<std::pair<std::string,CFunctionList<void()> > > pom;
  948. pom.push_back(std::pair<std::string,CFunctionList<void()> >("IOKAY.DEF",0));
  949. if (cancel)
  950. {
  951. pom.push_back(std::pair<std::string,CFunctionList<void()> >("ICANCEL.DEF",0));
  952. }
  953. int charperline = 35;
  954. if (pom.size() > 1)
  955. charperline = 50;
  956. GH.windows().createAndPushWindow<CSelWindow>(text, playerID, charperline, intComps, pom, askID);
  957. intComps[0]->clickPressed(GH.getCursorPosition());
  958. intComps[0]->clickReleased(GH.getCursorPosition());
  959. }
  960. }
  961. void CPlayerInterface::showTeleportDialog(TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  962. {
  963. EVENT_HANDLER_CALLED_BY_CLIENT;
  964. int choosenExit = -1;
  965. auto neededExit = std::make_pair(destinationTeleport, destinationTeleportPos);
  966. if (destinationTeleport != ObjectInstanceID() && vstd::contains(exits, neededExit))
  967. choosenExit = vstd::find_pos(exits, neededExit);
  968. cb->selectionMade(choosenExit, askID);
  969. }
  970. void CPlayerInterface::showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects)
  971. {
  972. EVENT_HANDLER_CALLED_BY_CLIENT;
  973. auto selectCallback = [=](int selection)
  974. {
  975. JsonNode reply(JsonNode::JsonType::DATA_INTEGER);
  976. reply.Integer() = selection;
  977. cb->sendQueryReply(reply, askID);
  978. };
  979. auto cancelCallback = [=]()
  980. {
  981. JsonNode reply(JsonNode::JsonType::DATA_NULL);
  982. cb->sendQueryReply(reply, askID);
  983. };
  984. const std::string localTitle = title.toString();
  985. const std::string localDescription = description.toString();
  986. std::vector<int> tempList;
  987. tempList.reserve(objects.size());
  988. for(auto item : objects)
  989. tempList.push_back(item.getNum());
  990. CComponent localIconC(icon);
  991. std::shared_ptr<CIntObject> localIcon = localIconC.image;
  992. localIconC.removeChild(localIcon.get(), false);
  993. std::shared_ptr<CObjectListWindow> wnd = std::make_shared<CObjectListWindow>(tempList, localIcon, localTitle, localDescription, selectCallback);
  994. wnd->onExit = cancelCallback;
  995. GH.windows().pushWindow(wnd);
  996. }
  997. void CPlayerInterface::tileRevealed(const std::unordered_set<int3> &pos)
  998. {
  999. EVENT_HANDLER_CALLED_BY_CLIENT;
  1000. //FIXME: wait for dialog? Magi hut/eye would benefit from this but may break other areas
  1001. adventureInt->onMapTilesChanged(pos);
  1002. }
  1003. void CPlayerInterface::tileHidden(const std::unordered_set<int3> &pos)
  1004. {
  1005. EVENT_HANDLER_CALLED_BY_CLIENT;
  1006. adventureInt->onMapTilesChanged(pos);
  1007. }
  1008. void CPlayerInterface::openHeroWindow(const CGHeroInstance *hero)
  1009. {
  1010. boost::unique_lock<boost::recursive_mutex> un(*pim);
  1011. GH.windows().createAndPushWindow<CHeroWindow>(hero);
  1012. }
  1013. void CPlayerInterface::availableCreaturesChanged( const CGDwelling *town )
  1014. {
  1015. EVENT_HANDLER_CALLED_BY_CLIENT;
  1016. if (const CGTownInstance * townObj = dynamic_cast<const CGTownInstance*>(town))
  1017. {
  1018. for (auto fortScreen : GH.windows().findWindows<CFortScreen>())
  1019. fortScreen->creaturesChangedEventHandler();
  1020. for (auto castleInterface : GH.windows().findWindows<CCastleInterface>())
  1021. castleInterface->creaturesChangedEventHandler();
  1022. if (townObj)
  1023. for (auto ki : GH.windows().findWindows<CKingdomInterface>())
  1024. ki->townChanged(townObj);
  1025. }
  1026. else if(town && GH.windows().count() > 0 && (town->ID == Obj::CREATURE_GENERATOR1
  1027. || town->ID == Obj::CREATURE_GENERATOR4 || town->ID == Obj::WAR_MACHINE_FACTORY))
  1028. {
  1029. for (auto crw : GH.windows().findWindows<CRecruitmentWindow>())
  1030. if (crw->dwelling == town)
  1031. crw->availableCreaturesChanged();
  1032. }
  1033. }
  1034. void CPlayerInterface::heroBonusChanged( const CGHeroInstance *hero, const Bonus &bonus, bool gain )
  1035. {
  1036. EVENT_HANDLER_CALLED_BY_CLIENT;
  1037. if (bonus.type == BonusType::NONE)
  1038. return;
  1039. adventureInt->onHeroChanged(hero);
  1040. if ((bonus.type == BonusType::FLYING_MOVEMENT || bonus.type == BonusType::WATER_WALKING) && !gain)
  1041. {
  1042. //recalculate paths because hero has lost bonus influencing pathfinding
  1043. localState->erasePath(hero);
  1044. }
  1045. }
  1046. void CPlayerInterface::saveGame( BinarySerializer & h, const int version )
  1047. {
  1048. EVENT_HANDLER_CALLED_BY_CLIENT;
  1049. localState->serialize(h, version);
  1050. }
  1051. void CPlayerInterface::loadGame( BinaryDeserializer & h, const int version )
  1052. {
  1053. EVENT_HANDLER_CALLED_BY_CLIENT;
  1054. localState->serialize(h, version);
  1055. firstCall = -1;
  1056. }
  1057. void CPlayerInterface::moveHero( const CGHeroInstance *h, const CGPath& path )
  1058. {
  1059. LOG_TRACE(logGlobal);
  1060. if (!LOCPLINT->makingTurn)
  1061. return;
  1062. if (!h)
  1063. return; //can't find hero
  1064. //It shouldn't be possible to move hero with open dialog (or dialog waiting in bg)
  1065. if (showingDialog->get() || !dialogs.empty())
  1066. return;
  1067. setMovementStatus(true);
  1068. if (localState->isHeroSleeping(h))
  1069. localState->setHeroAwaken(h);
  1070. boost::thread moveHeroTask(std::bind(&CPlayerInterface::doMoveHero,this,h,path));
  1071. }
  1072. void CPlayerInterface::showGarrisonDialog( const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, QueryID queryID)
  1073. {
  1074. EVENT_HANDLER_CALLED_BY_CLIENT;
  1075. auto onEnd = [=](){ cb->selectionMade(0, queryID); };
  1076. if (stillMoveHero.get() == DURING_MOVE && localState->hasPath(down) && localState->getPath(down).nodes.size() > 1) //to ignore calls on passing through garrisons
  1077. {
  1078. onEnd();
  1079. return;
  1080. }
  1081. waitForAllDialogs();
  1082. auto cgw = std::make_shared<CGarrisonWindow>(up, down, removableUnits);
  1083. cgw->quit->addCallback(onEnd);
  1084. GH.windows().pushWindow(cgw);
  1085. }
  1086. /**
  1087. * Shows the dialog that appears when right-clicking an artifact that can be assembled
  1088. * into a combinational one on an artifact screen. Does not require the combination of
  1089. * artifacts to be legal.
  1090. */
  1091. void CPlayerInterface::showArtifactAssemblyDialog(const Artifact * artifact, const Artifact * assembledArtifact, CFunctionList<bool()> onYes)
  1092. {
  1093. std::string text = artifact->getDescriptionTranslated();
  1094. text += "\n\n";
  1095. std::vector<std::shared_ptr<CComponent>> scs;
  1096. if(assembledArtifact)
  1097. {
  1098. // You possess all of the components to...
  1099. text += boost::str(boost::format(CGI->generaltexth->allTexts[732]) % assembledArtifact->getNameTranslated());
  1100. // Picture of assembled artifact at bottom.
  1101. auto sc = std::make_shared<CComponent>(CComponent::artifact, assembledArtifact->getIndex(), 0);
  1102. scs.push_back(sc);
  1103. }
  1104. else
  1105. {
  1106. // Do you wish to disassemble this artifact?
  1107. text += CGI->generaltexth->allTexts[733];
  1108. }
  1109. showYesNoDialog(text, onYes, nullptr, scs);
  1110. }
  1111. void CPlayerInterface::requestRealized( PackageApplied *pa )
  1112. {
  1113. EVENT_HANDLER_CALLED_BY_CLIENT;
  1114. if (pa->packType == typeList.getTypeID<MoveHero>() && stillMoveHero.get() == DURING_MOVE
  1115. && destinationTeleport == ObjectInstanceID())
  1116. stillMoveHero.setn(CONTINUE_MOVE);
  1117. if (destinationTeleport != ObjectInstanceID()
  1118. && pa->packType == typeList.getTypeID<QueryReply>()
  1119. && stillMoveHero.get() == DURING_MOVE)
  1120. { // After teleportation via CGTeleport object is finished
  1121. destinationTeleport = ObjectInstanceID();
  1122. destinationTeleportPos = int3(-1);
  1123. stillMoveHero.setn(CONTINUE_MOVE);
  1124. }
  1125. }
  1126. void CPlayerInterface::showHeroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2)
  1127. {
  1128. heroExchangeStarted(hero1, hero2, QueryID(-1));
  1129. }
  1130. void CPlayerInterface::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  1131. {
  1132. EVENT_HANDLER_CALLED_BY_CLIENT;
  1133. GH.windows().createAndPushWindow<CExchangeWindow>(hero1, hero2, query);
  1134. }
  1135. void CPlayerInterface::beforeObjectPropertyChanged(const SetObjectProperty * sop)
  1136. {
  1137. if (sop->what == ObjProperty::OWNER)
  1138. {
  1139. const CGObjectInstance * obj = cb->getObj(sop->id);
  1140. if(obj->ID == Obj::TOWN)
  1141. {
  1142. auto town = static_cast<const CGTownInstance *>(obj);
  1143. if(obj->tempOwner == playerID)
  1144. {
  1145. localState->removeOwnedTown(town);
  1146. adventureInt->onTownChanged(town);
  1147. }
  1148. }
  1149. }
  1150. }
  1151. void CPlayerInterface::objectPropertyChanged(const SetObjectProperty * sop)
  1152. {
  1153. EVENT_HANDLER_CALLED_BY_CLIENT;
  1154. if (sop->what == ObjProperty::OWNER)
  1155. {
  1156. const CGObjectInstance * obj = cb->getObj(sop->id);
  1157. if(obj->ID == Obj::TOWN)
  1158. {
  1159. auto town = static_cast<const CGTownInstance *>(obj);
  1160. if(obj->tempOwner == playerID)
  1161. {
  1162. localState->addOwnedTown(town);
  1163. adventureInt->onTownChanged(town);
  1164. }
  1165. }
  1166. //redraw minimap if owner changed
  1167. std::set<int3> pos = obj->getBlockedPos();
  1168. std::unordered_set<int3> upos(pos.begin(), pos.end());
  1169. adventureInt->onMapTilesChanged(upos);
  1170. assert(cb->getTownsInfo().size() == localState->getOwnedTowns().size());
  1171. }
  1172. }
  1173. void CPlayerInterface::initializeHeroTownList()
  1174. {
  1175. if(localState->getWanderingHeroes().empty())
  1176. {
  1177. for(auto & hero : cb->getHeroesInfo())
  1178. {
  1179. if(!hero->inTownGarrison)
  1180. localState->addWanderingHero(hero);
  1181. }
  1182. }
  1183. if(localState->getOwnedTowns().empty())
  1184. {
  1185. for(auto & town : cb->getTownsInfo())
  1186. localState->addOwnedTown(town);
  1187. }
  1188. if(adventureInt)
  1189. adventureInt->onHeroChanged(nullptr);
  1190. }
  1191. void CPlayerInterface::showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level)
  1192. {
  1193. EVENT_HANDLER_CALLED_BY_CLIENT;
  1194. waitWhileDialog();
  1195. auto recruitCb = [=](CreatureID id, int count)
  1196. {
  1197. LOCPLINT->cb->recruitCreatures(dwelling, dst, id, count, -1);
  1198. };
  1199. GH.windows().createAndPushWindow<CRecruitmentWindow>(dwelling, level, dst, recruitCb);
  1200. }
  1201. void CPlayerInterface::waitWhileDialog(bool unlockPim)
  1202. {
  1203. if (GH.amIGuiThread())
  1204. {
  1205. logGlobal->warn("Cannot wait for dialogs in gui thread (deadlock risk)!");
  1206. return;
  1207. }
  1208. auto unlock = vstd::makeUnlockGuardIf(*pim, unlockPim);
  1209. boost::unique_lock<boost::mutex> un(showingDialog->mx);
  1210. while(showingDialog->data)
  1211. showingDialog->cond.wait(un);
  1212. }
  1213. void CPlayerInterface::showShipyardDialog(const IShipyard *obj)
  1214. {
  1215. EVENT_HANDLER_CALLED_BY_CLIENT;
  1216. auto state = obj->shipyardStatus();
  1217. TResources cost;
  1218. obj->getBoatCost(cost);
  1219. GH.windows().createAndPushWindow<CShipyardWindow>(cost, state, obj->getBoatType(), [=](){ cb->buildBoat(obj); });
  1220. }
  1221. void CPlayerInterface::newObject( const CGObjectInstance * obj )
  1222. {
  1223. EVENT_HANDLER_CALLED_BY_CLIENT;
  1224. //we might have built a boat in shipyard in opened town screen
  1225. if (obj->ID == Obj::BOAT
  1226. && LOCPLINT->castleInt
  1227. && obj->visitablePos() == LOCPLINT->castleInt->town->bestLocation())
  1228. {
  1229. CCS->soundh->playSound(soundBase::newBuilding);
  1230. LOCPLINT->castleInt->addBuilding(BuildingID::SHIP);
  1231. }
  1232. }
  1233. void CPlayerInterface::centerView (int3 pos, int focusTime)
  1234. {
  1235. EVENT_HANDLER_CALLED_BY_CLIENT;
  1236. waitWhileDialog();
  1237. CCS->curh->hide();
  1238. adventureInt->centerOnTile(pos);
  1239. if (focusTime)
  1240. {
  1241. GH.windows().totalRedraw();
  1242. {
  1243. auto unlockPim = vstd::makeUnlockGuard(*pim);
  1244. IgnoreEvents ignore(*this);
  1245. boost::this_thread::sleep(boost::posix_time::milliseconds(focusTime));
  1246. }
  1247. }
  1248. CCS->curh->show();
  1249. }
  1250. void CPlayerInterface::objectRemoved(const CGObjectInstance * obj)
  1251. {
  1252. EVENT_HANDLER_CALLED_BY_CLIENT;
  1253. if(LOCPLINT->cb->getCurrentPlayer() == playerID && obj->getRemovalSound())
  1254. {
  1255. waitWhileDialog();
  1256. CCS->soundh->playSound(obj->getRemovalSound().value());
  1257. }
  1258. CGI->mh->waitForOngoingAnimations();
  1259. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  1260. {
  1261. const CGHeroInstance * h = static_cast<const CGHeroInstance *>(obj);
  1262. heroKilled(h);
  1263. }
  1264. GH.fakeMouseMove();
  1265. }
  1266. void CPlayerInterface::objectRemovedAfter()
  1267. {
  1268. EVENT_HANDLER_CALLED_BY_CLIENT;
  1269. adventureInt->onMapTilesChanged(boost::none);
  1270. // visiting or garrisoned hero removed - recreate castle window
  1271. if (castleInt)
  1272. openTownWindow(castleInt->town);
  1273. for (auto ki : GH.windows().findWindows<CKingdomInterface>())
  1274. ki->heroRemoved();
  1275. }
  1276. void CPlayerInterface::playerBlocked(int reason, bool start)
  1277. {
  1278. if(reason == PlayerBlocked::EReason::UPCOMING_BATTLE)
  1279. {
  1280. if(CSH->howManyPlayerInterfaces() > 1 && LOCPLINT != this && LOCPLINT->makingTurn == false)
  1281. {
  1282. //one of our players who isn't last in order got attacked not by our another player (happens for example in hotseat mode)
  1283. LOCPLINT = this;
  1284. GH.curInt = this;
  1285. adventureInt->onCurrentPlayerChanged(playerID);
  1286. std::string msg = CGI->generaltexth->translate("vcmi.adventureMap.playerAttacked");
  1287. boost::replace_first(msg, "%s", cb->getStartInfo()->playerInfos.find(playerID)->second.name);
  1288. std::vector<std::shared_ptr<CComponent>> cmp;
  1289. cmp.push_back(std::make_shared<CComponent>(CComponent::flag, playerID.getNum(), 0));
  1290. makingTurn = true; //workaround for stiff showInfoDialog implementation
  1291. showInfoDialog(msg, cmp);
  1292. makingTurn = false;
  1293. }
  1294. }
  1295. }
  1296. void CPlayerInterface::update()
  1297. {
  1298. // Make sure that gamestate won't change when GUI objects may obtain its parts on event processing or drawing request
  1299. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  1300. // While mutexes were locked away we may be have stopped being the active interface
  1301. if (LOCPLINT != this)
  1302. return;
  1303. //if there are any waiting dialogs, show them
  1304. if ((CSH->howManyPlayerInterfaces() <= 1 || makingTurn) && !dialogs.empty() && !showingDialog->get())
  1305. {
  1306. showingDialog->set(true);
  1307. GH.windows().pushWindow(dialogs.front());
  1308. dialogs.pop_front();
  1309. }
  1310. assert(adventureInt);
  1311. // Handles mouse and key input
  1312. GH.handleEvents();
  1313. GH.windows().simpleRedraw();
  1314. }
  1315. int CPlayerInterface::getLastIndex( std::string namePrefix)
  1316. {
  1317. using namespace boost::filesystem;
  1318. using namespace boost::algorithm;
  1319. path gamesDir = VCMIDirs::get().userSavePath();
  1320. std::map<std::time_t, int> dates; //save number => datestamp
  1321. const directory_iterator enddir;
  1322. if (!exists(gamesDir))
  1323. create_directory(gamesDir);
  1324. else
  1325. for (directory_iterator dir(gamesDir); dir != enddir; ++dir)
  1326. {
  1327. if (is_regular_file(dir->status()))
  1328. {
  1329. std::string name = dir->path().filename().string();
  1330. if (starts_with(name, namePrefix) && ends_with(name, ".vcgm1"))
  1331. {
  1332. char nr = name[namePrefix.size()];
  1333. if (std::isdigit(nr))
  1334. dates[last_write_time(dir->path())] = boost::lexical_cast<int>(nr);
  1335. }
  1336. }
  1337. }
  1338. if (!dates.empty())
  1339. return (--dates.end())->second; //return latest file number
  1340. return 0;
  1341. }
  1342. void CPlayerInterface::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult )
  1343. {
  1344. EVENT_HANDLER_CALLED_BY_CLIENT;
  1345. if (player == playerID)
  1346. {
  1347. if (victoryLossCheckResult.loss())
  1348. showInfoDialog(CGI->generaltexth->allTexts[95]);
  1349. assert(GH.curInt == LOCPLINT);
  1350. auto previousInterface = LOCPLINT; //without multiple player interfaces some of lines below are useless, but for hotseat we wanna swap player interface temporarily
  1351. LOCPLINT = this; //this is needed for dialog to show and avoid freeze, dialog showing logic should be reworked someday
  1352. GH.curInt = this; //waiting for dialogs requires this to get events
  1353. if(!makingTurn)
  1354. {
  1355. makingTurn = true; //also needed for dialog to show with current implementation
  1356. waitForAllDialogs();
  1357. makingTurn = false;
  1358. }
  1359. else
  1360. waitForAllDialogs();
  1361. GH.curInt = previousInterface;
  1362. LOCPLINT = previousInterface;
  1363. if(CSH->howManyPlayerInterfaces() == 1 && !settings["session"]["spectate"].Bool()) //all human players eliminated
  1364. {
  1365. if(adventureInt)
  1366. {
  1367. GH.terminate_cond->setn(true);
  1368. GH.windows().popWindows(GH.windows().count());
  1369. adventureInt.reset();
  1370. }
  1371. }
  1372. if (victoryLossCheckResult.victory() && LOCPLINT == this)
  1373. {
  1374. // end game if current human player has won
  1375. CSH->sendClientDisconnecting();
  1376. requestReturningToMainMenu(true);
  1377. }
  1378. else if(CSH->howManyPlayerInterfaces() == 1 && !settings["session"]["spectate"].Bool())
  1379. {
  1380. //all human players eliminated
  1381. CSH->sendClientDisconnecting();
  1382. requestReturningToMainMenu(false);
  1383. }
  1384. if (GH.curInt == this)
  1385. GH.curInt = nullptr;
  1386. }
  1387. else
  1388. {
  1389. if (victoryLossCheckResult.loss() && cb->getPlayerStatus(playerID) == EPlayerStatus::INGAME) //enemy has lost
  1390. {
  1391. MetaString message = victoryLossCheckResult.messageToSelf;
  1392. message.appendLocalString(EMetaText::COLOR, player.getNum());
  1393. showInfoDialog(message.toString(), std::vector<std::shared_ptr<CComponent>>(1, std::make_shared<CComponent>(CComponent::flag, player.getNum(), 0)));
  1394. }
  1395. }
  1396. }
  1397. void CPlayerInterface::playerBonusChanged( const Bonus &bonus, bool gain )
  1398. {
  1399. EVENT_HANDLER_CALLED_BY_CLIENT;
  1400. }
  1401. void CPlayerInterface::showPuzzleMap()
  1402. {
  1403. EVENT_HANDLER_CALLED_BY_CLIENT;
  1404. waitWhileDialog();
  1405. //TODO: interface should not know the real position of Grail...
  1406. double ratio = 0;
  1407. int3 grailPos = cb->getGrailPos(&ratio);
  1408. GH.windows().createAndPushWindow<CPuzzleWindow>(grailPos, ratio);
  1409. }
  1410. void CPlayerInterface::viewWorldMap()
  1411. {
  1412. adventureInt->openWorldView();
  1413. }
  1414. void CPlayerInterface::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  1415. {
  1416. EVENT_HANDLER_CALLED_BY_CLIENT;
  1417. if(GH.windows().topWindow<CSpellWindow>())
  1418. GH.windows().popWindows(1);
  1419. if(spellID == SpellID::FLY || spellID == SpellID::WATER_WALK)
  1420. localState->erasePath(caster);
  1421. const spells::Spell * spell = CGI->spells()->getByIndex(spellID);
  1422. auto castSoundPath = spell->getCastSound();
  1423. if(!castSoundPath.empty())
  1424. CCS->soundh->playSound(castSoundPath);
  1425. }
  1426. void CPlayerInterface::tryDiggging(const CGHeroInstance * h)
  1427. {
  1428. int msgToShow = -1;
  1429. const auto diggingStatus = h->diggingStatus();
  1430. switch(diggingStatus)
  1431. {
  1432. case EDiggingStatus::CAN_DIG:
  1433. break;
  1434. case EDiggingStatus::LACK_OF_MOVEMENT:
  1435. msgToShow = 56; //"Digging for artifacts requires a whole day, try again tomorrow."
  1436. break;
  1437. case EDiggingStatus::TILE_OCCUPIED:
  1438. msgToShow = 97; //Try searching on clear ground.
  1439. break;
  1440. case EDiggingStatus::WRONG_TERRAIN:
  1441. msgToShow = 60; ////Try looking on land!
  1442. break;
  1443. case EDiggingStatus::BACKPACK_IS_FULL:
  1444. msgToShow = 247; //Searching for the Grail is fruitless...
  1445. break;
  1446. default:
  1447. assert(0);
  1448. }
  1449. if(msgToShow < 0)
  1450. cb->dig(h);
  1451. else
  1452. showInfoDialog(CGI->generaltexth->allTexts[msgToShow]);
  1453. }
  1454. void CPlayerInterface::battleNewRoundFirst( int round )
  1455. {
  1456. EVENT_HANDLER_CALLED_BY_CLIENT;
  1457. BATTLE_EVENT_POSSIBLE_RETURN;
  1458. battleInt->newRoundFirst(round);
  1459. }
  1460. void CPlayerInterface::stopMovement()
  1461. {
  1462. if (stillMoveHero.get() == DURING_MOVE)//if we are in the middle of hero movement
  1463. stillMoveHero.setn(STOP_MOVE); //after showing dialog movement will be stopped
  1464. }
  1465. void CPlayerInterface::showMarketWindow(const IMarket *market, const CGHeroInstance *visitor)
  1466. {
  1467. EVENT_HANDLER_CALLED_BY_CLIENT;
  1468. if(market->allowsTrade(EMarketMode::ARTIFACT_EXP) && visitor->getAlignment() != EAlignment::EVIL)
  1469. GH.windows().createAndPushWindow<CAltarWindow>(market, visitor, EMarketMode::ARTIFACT_EXP);
  1470. else if(market->allowsTrade(EMarketMode::CREATURE_EXP) && visitor->getAlignment() != EAlignment::GOOD)
  1471. GH.windows().createAndPushWindow<CAltarWindow>(market, visitor, EMarketMode::CREATURE_EXP);
  1472. else if(market->allowsTrade(EMarketMode::CREATURE_UNDEAD))
  1473. GH.windows().createAndPushWindow<CTransformerWindow>(market, visitor);
  1474. else if(!market->availableModes().empty())
  1475. GH.windows().createAndPushWindow<CMarketplaceWindow>(market, visitor, market->availableModes().front());
  1476. }
  1477. void CPlayerInterface::showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor)
  1478. {
  1479. EVENT_HANDLER_CALLED_BY_CLIENT;
  1480. GH.windows().createAndPushWindow<CUniversityWindow>(visitor, market);
  1481. }
  1482. void CPlayerInterface::showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor)
  1483. {
  1484. EVENT_HANDLER_CALLED_BY_CLIENT;
  1485. GH.windows().createAndPushWindow<CHillFortWindow>(visitor, object);
  1486. }
  1487. void CPlayerInterface::availableArtifactsChanged(const CGBlackMarket * bm)
  1488. {
  1489. EVENT_HANDLER_CALLED_BY_CLIENT;
  1490. for (auto cmw : GH.windows().findWindows<CMarketplaceWindow>())
  1491. cmw->artifactsChanged(false);
  1492. }
  1493. void CPlayerInterface::showTavernWindow(const CGObjectInstance *townOrTavern)
  1494. {
  1495. EVENT_HANDLER_CALLED_BY_CLIENT;
  1496. GH.windows().createAndPushWindow<CTavernWindow>(townOrTavern);
  1497. }
  1498. void CPlayerInterface::showThievesGuildWindow (const CGObjectInstance * obj)
  1499. {
  1500. EVENT_HANDLER_CALLED_BY_CLIENT;
  1501. GH.windows().createAndPushWindow<CThievesGuildWindow>(obj);
  1502. }
  1503. void CPlayerInterface::showQuestLog()
  1504. {
  1505. EVENT_HANDLER_CALLED_BY_CLIENT;
  1506. GH.windows().createAndPushWindow<CQuestLog>(LOCPLINT->cb->getMyQuests());
  1507. }
  1508. void CPlayerInterface::showShipyardDialogOrProblemPopup(const IShipyard *obj)
  1509. {
  1510. if (obj->shipyardStatus() != IBoatGenerator::GOOD)
  1511. {
  1512. MetaString txt;
  1513. obj->getProblemText(txt);
  1514. showInfoDialog(txt.toString());
  1515. }
  1516. else
  1517. showShipyardDialog(obj);
  1518. }
  1519. void CPlayerInterface::requestReturningToMainMenu(bool won)
  1520. {
  1521. if(won && cb->getStartInfo()->campState)
  1522. CSH->startCampaignScenario(cb->getStartInfo()->campState);
  1523. else
  1524. {
  1525. GH.dispatchMainThread(
  1526. []()
  1527. {
  1528. CSH->endGameplay();
  1529. GH.defActionsDef = 63;
  1530. CMM->menu->switchToTab("main");
  1531. }
  1532. );
  1533. }
  1534. }
  1535. void CPlayerInterface::askToAssembleArtifact(const ArtifactLocation &al)
  1536. {
  1537. auto hero = std::visit(HeroObjectRetriever(), al.artHolder);
  1538. if(hero)
  1539. {
  1540. auto art = hero->getArt(al.slot);
  1541. if(art == nullptr)
  1542. {
  1543. logGlobal->error("artifact location %d points to nothing",
  1544. al.slot.num);
  1545. return;
  1546. }
  1547. ArtifactUtilsClient::askToAssemble(hero, al.slot);
  1548. }
  1549. }
  1550. void CPlayerInterface::artifactPut(const ArtifactLocation &al)
  1551. {
  1552. EVENT_HANDLER_CALLED_BY_CLIENT;
  1553. auto hero = std::visit(HeroObjectRetriever(), al.artHolder);
  1554. adventureInt->onHeroChanged(hero);
  1555. }
  1556. void CPlayerInterface::artifactRemoved(const ArtifactLocation &al)
  1557. {
  1558. EVENT_HANDLER_CALLED_BY_CLIENT;
  1559. auto hero = std::visit(HeroObjectRetriever(), al.artHolder);
  1560. adventureInt->onHeroChanged(hero);
  1561. for(auto artWin : GH.windows().findWindows<CArtifactHolder>())
  1562. artWin->artifactRemoved(al);
  1563. waitWhileDialog();
  1564. }
  1565. void CPlayerInterface::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  1566. {
  1567. EVENT_HANDLER_CALLED_BY_CLIENT;
  1568. auto hero = std::visit(HeroObjectRetriever(), dst.artHolder);
  1569. adventureInt->onHeroChanged(hero);
  1570. bool redraw = true;
  1571. // If a bulk transfer has arrived, then redrawing only the last art movement.
  1572. if(numOfMovedArts != 0)
  1573. {
  1574. numOfMovedArts--;
  1575. if(numOfMovedArts != 0)
  1576. redraw = false;
  1577. }
  1578. for(auto artWin : GH.windows().findWindows<CArtifactHolder>())
  1579. artWin->artifactMoved(src, dst, redraw);
  1580. waitWhileDialog();
  1581. }
  1582. void CPlayerInterface::bulkArtMovementStart(size_t numOfArts)
  1583. {
  1584. numOfMovedArts = numOfArts;
  1585. }
  1586. void CPlayerInterface::artifactAssembled(const ArtifactLocation &al)
  1587. {
  1588. EVENT_HANDLER_CALLED_BY_CLIENT;
  1589. auto hero = std::visit(HeroObjectRetriever(), al.artHolder);
  1590. adventureInt->onHeroChanged(hero);
  1591. for(auto artWin : GH.windows().findWindows<CArtifactHolder>())
  1592. artWin->artifactAssembled(al);
  1593. }
  1594. void CPlayerInterface::artifactDisassembled(const ArtifactLocation &al)
  1595. {
  1596. EVENT_HANDLER_CALLED_BY_CLIENT;
  1597. auto hero = std::visit(HeroObjectRetriever(), al.artHolder);
  1598. adventureInt->onHeroChanged(hero);
  1599. for(auto artWin : GH.windows().findWindows<CArtifactHolder>())
  1600. artWin->artifactDisassembled(al);
  1601. }
  1602. void CPlayerInterface::waitForAllDialogs(bool unlockPim)
  1603. {
  1604. while(!dialogs.empty())
  1605. {
  1606. auto unlock = vstd::makeUnlockGuardIf(*pim, unlockPim);
  1607. boost::this_thread::sleep(boost::posix_time::milliseconds(5));
  1608. }
  1609. waitWhileDialog(unlockPim);
  1610. }
  1611. void CPlayerInterface::proposeLoadingGame()
  1612. {
  1613. showYesNoDialog(
  1614. CGI->generaltexth->allTexts[68],
  1615. []()
  1616. {
  1617. GH.dispatchMainThread(
  1618. []()
  1619. {
  1620. CSH->endGameplay();
  1621. GH.defActionsDef = 63;
  1622. CMM->menu->switchToTab("load");
  1623. }
  1624. );
  1625. },
  1626. nullptr
  1627. );
  1628. }
  1629. bool CPlayerInterface::capturedAllEvents()
  1630. {
  1631. if(duringMovement)
  1632. {
  1633. //just inform that we are capturing events. they will be processed by heroMoved() in client thread.
  1634. return true;
  1635. }
  1636. bool needToLockAdventureMap = adventureInt && adventureInt->isActive() && CGI->mh->hasOngoingAnimations();
  1637. if (ignoreEvents || needToLockAdventureMap || isAutoFightOn)
  1638. {
  1639. GH.input().ignoreEventsUntilInput();
  1640. return true;
  1641. }
  1642. return false;
  1643. }
  1644. void CPlayerInterface::setMovementStatus(bool value)
  1645. {
  1646. duringMovement = value;
  1647. if (value)
  1648. {
  1649. CCS->curh->hide();
  1650. }
  1651. else
  1652. {
  1653. CCS->curh->show();
  1654. }
  1655. }
  1656. void CPlayerInterface::doMoveHero(const CGHeroInstance * h, CGPath path)
  1657. {
  1658. int i = 1;
  1659. auto getObj = [&](int3 coord, bool ignoreHero)
  1660. {
  1661. return cb->getTile(h->convertToVisitablePos(coord))->topVisitableObj(ignoreHero);
  1662. };
  1663. auto isTeleportAction = [&](EPathNodeAction action) -> bool
  1664. {
  1665. if (action != EPathNodeAction::TELEPORT_NORMAL &&
  1666. action != EPathNodeAction::TELEPORT_BLOCKING_VISIT &&
  1667. action != EPathNodeAction::TELEPORT_BATTLE)
  1668. {
  1669. return false;
  1670. }
  1671. return true;
  1672. };
  1673. auto getDestTeleportObj = [&](const CGObjectInstance * currentObject, const CGObjectInstance * nextObjectTop, const CGObjectInstance * nextObject) -> const CGObjectInstance *
  1674. {
  1675. if (CGTeleport::isConnected(currentObject, nextObjectTop))
  1676. return nextObjectTop;
  1677. if (nextObjectTop && nextObjectTop->ID == Obj::HERO &&
  1678. CGTeleport::isConnected(currentObject, nextObject))
  1679. {
  1680. return nextObject;
  1681. }
  1682. return nullptr;
  1683. };
  1684. boost::unique_lock<boost::mutex> un(stillMoveHero.mx);
  1685. stillMoveHero.data = CONTINUE_MOVE;
  1686. auto doMovement = [&](int3 dst, bool transit)
  1687. {
  1688. stillMoveHero.data = WAITING_MOVE;
  1689. cb->moveHero(h, dst, transit);
  1690. while(stillMoveHero.data != STOP_MOVE && stillMoveHero.data != CONTINUE_MOVE)
  1691. stillMoveHero.cond.wait(un);
  1692. };
  1693. {
  1694. for (auto & elem : path.nodes)
  1695. elem.coord = h->convertFromVisitablePos(elem.coord);
  1696. int soundChannel = -1;
  1697. std::string soundName;
  1698. auto getMovementSoundFor = [&](const CGHeroInstance * hero, int3 posPrev, int3 posNext, EPathNodeAction moveType) -> std::string
  1699. {
  1700. if (moveType == EPathNodeAction::TELEPORT_BATTLE || moveType == EPathNodeAction::TELEPORT_BLOCKING_VISIT || moveType == EPathNodeAction::TELEPORT_NORMAL)
  1701. return "";
  1702. if (moveType == EPathNodeAction::EMBARK || moveType == EPathNodeAction::DISEMBARK)
  1703. return "";
  1704. if (moveType == EPathNodeAction::BLOCKING_VISIT)
  1705. return "";
  1706. // flying movement sound
  1707. if (hero->hasBonusOfType(BonusType::FLYING_MOVEMENT))
  1708. return "HORSE10.wav";
  1709. auto prevTile = cb->getTile(h->convertToVisitablePos(posPrev));
  1710. auto nextTile = cb->getTile(h->convertToVisitablePos(posNext));
  1711. auto prevRoad = prevTile->roadType;
  1712. auto nextRoad = nextTile->roadType;
  1713. bool movingOnRoad = prevRoad->getId() != Road::NO_ROAD && nextRoad->getId() != Road::NO_ROAD;
  1714. if (movingOnRoad)
  1715. return nextTile->terType->horseSound;
  1716. else
  1717. return nextTile->terType->horseSoundPenalty;
  1718. };
  1719. auto canStop = [&](CGPathNode * node) -> bool
  1720. {
  1721. if (node->layer == EPathfindingLayer::LAND || node->layer == EPathfindingLayer::SAIL)
  1722. return true;
  1723. if (node->accessible == EPathAccessibility::ACCESSIBLE)
  1724. return true;
  1725. return false;
  1726. };
  1727. for (i=(int)path.nodes.size()-1; i>0 && (stillMoveHero.data == CONTINUE_MOVE || !canStop(&path.nodes[i])); i--)
  1728. {
  1729. int3 prevCoord = path.nodes[i].coord;
  1730. int3 nextCoord = path.nodes[i-1].coord;
  1731. auto prevObject = getObj(prevCoord, prevCoord == h->pos);
  1732. auto nextObjectTop = getObj(nextCoord, false);
  1733. auto nextObject = getObj(nextCoord, true);
  1734. auto destTeleportObj = getDestTeleportObj(prevObject, nextObjectTop, nextObject);
  1735. if (isTeleportAction(path.nodes[i-1].action) && destTeleportObj != nullptr)
  1736. {
  1737. CCS->soundh->stopSound(soundChannel);
  1738. destinationTeleport = destTeleportObj->id;
  1739. destinationTeleportPos = nextCoord;
  1740. doMovement(h->pos, false);
  1741. if (path.nodes[i-1].action == EPathNodeAction::TELEPORT_BLOCKING_VISIT
  1742. || path.nodes[i-1].action == EPathNodeAction::TELEPORT_BATTLE)
  1743. {
  1744. destinationTeleport = ObjectInstanceID();
  1745. destinationTeleportPos = int3(-1);
  1746. }
  1747. if(i != path.nodes.size() - 1)
  1748. {
  1749. soundName = getMovementSoundFor(h, prevCoord, nextCoord, path.nodes[i-1].action);
  1750. if (!soundName.empty())
  1751. soundChannel = CCS->soundh->playSound(soundName, -1);
  1752. else
  1753. soundChannel = -1;
  1754. }
  1755. continue;
  1756. }
  1757. if (path.nodes[i-1].turns)
  1758. { //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1759. stillMoveHero.data = STOP_MOVE;
  1760. break;
  1761. }
  1762. {
  1763. // Start a new sound for the hero movement or let the existing one carry on.
  1764. std::string newSoundName = getMovementSoundFor(h, prevCoord, nextCoord, path.nodes[i-1].action);
  1765. if(newSoundName != soundName)
  1766. {
  1767. soundName = newSoundName;
  1768. CCS->soundh->stopSound(soundChannel);
  1769. if (!soundName.empty())
  1770. soundChannel = CCS->soundh->playSound(soundName, -1);
  1771. else
  1772. soundChannel = -1;
  1773. }
  1774. }
  1775. assert(h->pos.z == nextCoord.z); // Z should change only if it's movement via teleporter and in this case this code shouldn't be executed at all
  1776. int3 endpos(nextCoord.x, nextCoord.y, h->pos.z);
  1777. logGlobal->trace("Requesting hero movement to %s", endpos.toString());
  1778. bool useTransit = false;
  1779. if ((i-2 >= 0) // Check there is node after next one; otherwise transit is pointless
  1780. && (CGTeleport::isConnected(nextObjectTop, getObj(path.nodes[i-2].coord, false))
  1781. || CGTeleport::isTeleport(nextObjectTop)))
  1782. { // Hero should be able to go through object if it's allow transit
  1783. useTransit = true;
  1784. }
  1785. else if (path.nodes[i-1].layer == EPathfindingLayer::AIR)
  1786. useTransit = true;
  1787. doMovement(endpos, useTransit);
  1788. logGlobal->trace("Resuming %s", __FUNCTION__);
  1789. bool guarded = cb->isInTheMap(cb->getGuardingCreaturePosition(endpos - int3(1, 0, 0)));
  1790. if ((!useTransit && guarded) || showingDialog->get() == true) // Abort movement if a guard was fought or there is a dialog to display (Mantis #1136)
  1791. break;
  1792. }
  1793. CCS->soundh->stopSound(soundChannel);
  1794. }
  1795. //Update cursor so icon can change if needed when it reappears; doesn;'t apply if a dialog box pops up at the end of the movement
  1796. if (!showingDialog->get())
  1797. GH.fakeMouseMove();
  1798. CGI->mh->waitForOngoingAnimations();
  1799. setMovementStatus(false);
  1800. }
  1801. void CPlayerInterface::showWorldViewEx(const std::vector<ObjectPosInfo>& objectPositions, bool showTerrain)
  1802. {
  1803. EVENT_HANDLER_CALLED_BY_CLIENT;
  1804. adventureInt->openWorldView(objectPositions, showTerrain );
  1805. }