CPlayerInterface.cpp 63 KB

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