CPlayerInterface.cpp 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856
  1. #include "StdInc.h"
  2. #include "windows/CAdvmapInterface.h"
  3. #include "battle/CBattleInterface.h"
  4. #include "battle/CBattleInterfaceClasses.h"
  5. #include "../CCallback.h"
  6. #include "windows/CCastleInterface.h"
  7. #include "gui/CCursorHandler.h"
  8. #include "windows/CKingdomInterface.h"
  9. #include "CGameInfo.h"
  10. #include "windows/CHeroWindow.h"
  11. #include "windows/CCreatureWindow.h"
  12. #include "windows/CQuestLog.h"
  13. #include "CMessage.h"
  14. #include "CPlayerInterface.h"
  15. #include "gui/SDL_Extensions.h"
  16. #include "widgets/CComponent.h"
  17. #include "windows/CTradeWindow.h"
  18. #include "../lib/CConfigHandler.h"
  19. #include "battle/CCreatureAnimation.h"
  20. #include "Graphics.h"
  21. #include "windows/GUIClasses.h"
  22. #include "../lib/CArtHandler.h"
  23. #include "../lib/CGeneralTextHandler.h"
  24. #include "../lib/CHeroHandler.h"
  25. #include "../lib/serializer/CTypeList.h"
  26. #include "../lib/serializer/BinaryDeserializer.h"
  27. #include "../lib/serializer/BinarySerializer.h"
  28. #include "../lib/spells/CSpellHandler.h"
  29. #include "../lib/CTownHandler.h"
  30. #include "../lib/mapObjects/CObjectClassesHandler.h" // For displaying correct UI when interacting with objects
  31. #include "../lib/CStack.h"
  32. #include "../lib/JsonNode.h"
  33. #include "CMusicHandler.h"
  34. #include "../lib/CondSh.h"
  35. #include "../lib/NetPacks.h"
  36. #include "../lib/mapping/CMap.h"
  37. #include "../lib/VCMIDirs.h"
  38. #include "mapHandler.h"
  39. #include "../lib/CStopWatch.h"
  40. #include "../lib/StartInfo.h"
  41. #include "../lib/CGameState.h"
  42. #include "../lib/CPlayerState.h"
  43. #include "../lib/GameConstants.h"
  44. #include "gui/CGuiHandler.h"
  45. #include "windows/InfoWindows.h"
  46. #include "../lib/UnlockGuard.h"
  47. #include <SDL.h>
  48. /*
  49. * CPlayerInterface.cpp, part of VCMI engine
  50. *
  51. * Authors: listed in file AUTHORS in main folder
  52. *
  53. * License: GNU General Public License v2.0 or later
  54. * Full text of license available in license.txt file, in main folder
  55. *
  56. */
  57. // The macro below is used to mark functions that are called by client when game state changes.
  58. // They all assume that CPlayerInterface::pim mutex is locked.
  59. #define EVENT_HANDLER_CALLED_BY_CLIENT
  60. // The macro marks functions that are run on a new thread by client.
  61. // They do not own any mutexes intiially.
  62. #define THREAD_CREATED_BY_CLIENT
  63. #define RETURN_IF_QUICK_COMBAT \
  64. if (isAutoFightOn && !battleInt) \
  65. return;
  66. #define BATTLE_EVENT_POSSIBLE_RETURN\
  67. if (LOCPLINT != this) \
  68. return; \
  69. RETURN_IF_QUICK_COMBAT
  70. using namespace CSDL_Ext;
  71. void processCommand(const std::string &message, CClient *&client);
  72. extern std::queue<SDL_Event> events;
  73. extern boost::mutex eventsM;
  74. boost::recursive_mutex * CPlayerInterface::pim = new boost::recursive_mutex;
  75. CPlayerInterface * LOCPLINT;
  76. CBattleInterface * CPlayerInterface::battleInt;
  77. enum EMoveState {STOP_MOVE, WAITING_MOVE, CONTINUE_MOVE, DURING_MOVE};
  78. CondSh<EMoveState> stillMoveHero(STOP_MOVE); //used during hero movement
  79. int CPlayerInterface::howManyPeople = 0;
  80. static bool objectBlitOrderSorter(const TerrainTileObject & a, const TerrainTileObject & b)
  81. {
  82. return CMapHandler::compareObjectBlitOrder(a.obj, b.obj);
  83. }
  84. struct HeroObjectRetriever : boost::static_visitor<const CGHeroInstance *>
  85. {
  86. const CGHeroInstance * operator()(const ConstTransitivePtr<CGHeroInstance> &h) const
  87. {
  88. return h;
  89. }
  90. const CGHeroInstance * operator()(const ConstTransitivePtr<CStackInstance> &s) const
  91. {
  92. return nullptr;
  93. }
  94. };
  95. CPlayerInterface::CPlayerInterface(PlayerColor Player)
  96. {
  97. logGlobal->traceStream() << "\tHuman player interface for player " << Player << " being constructed";
  98. destinationTeleport = ObjectInstanceID();
  99. destinationTeleportPos = int3(-1);
  100. observerInDuelMode = false;
  101. howManyPeople++;
  102. GH.defActionsDef = 0;
  103. LOCPLINT = this;
  104. curAction = nullptr;
  105. playerID=Player;
  106. human=true;
  107. currentSelection = nullptr;
  108. castleInt = nullptr;
  109. battleInt = nullptr;
  110. makingTurn = false;
  111. showingDialog = new CondSh<bool>(false);
  112. cingconsole = new CInGameConsole;
  113. GH.terminate_cond.set(false);
  114. firstCall = 1; //if loading will be overwritten in serialize
  115. autosaveCount = 0;
  116. isAutoFightOn = false;
  117. duringMovement = false;
  118. ignoreEvents = false;
  119. }
  120. CPlayerInterface::~CPlayerInterface()
  121. {
  122. logGlobal->traceStream() << "\tHuman player interface for player " << playerID << " being destructed";
  123. //howManyPeople--;
  124. delete showingDialog;
  125. delete cingconsole;
  126. if (LOCPLINT == this)
  127. LOCPLINT = nullptr;
  128. }
  129. void CPlayerInterface::init(std::shared_ptr<CCallback> CB)
  130. {
  131. cb = CB;
  132. if (observerInDuelMode)
  133. return;
  134. if (!towns.size() && !wanderingHeroes.size())
  135. initializeHeroTownList();
  136. // always recreate advmap interface to avoid possible memory-corruption bugs
  137. if (adventureInt)
  138. delete adventureInt;
  139. adventureInt = new CAdvMapInt();
  140. }
  141. void CPlayerInterface::yourTurn()
  142. {
  143. EVENT_HANDLER_CALLED_BY_CLIENT;
  144. {
  145. boost::unique_lock<boost::mutex> lock(eventsM); //block handling events until interface is ready
  146. LOCPLINT = this;
  147. GH.curInt = this;
  148. adventureInt->selection = nullptr;
  149. std::string prefix = settings["session"]["saveprefix"].String();
  150. if (firstCall)
  151. {
  152. if (howManyPeople == 1)
  153. adventureInt->setPlayer(playerID);
  154. autosaveCount = getLastIndex(prefix + "Autosave_");
  155. if (firstCall > 0) //new game, not loaded
  156. {
  157. int index = getLastIndex(prefix + "Newgame_");
  158. index %= SAVES_COUNT;
  159. cb->save("Saves/" + prefix + "Newgame_Autosave_" + boost::lexical_cast<std::string>(index + 1));
  160. }
  161. firstCall = 0;
  162. }
  163. else if (cb->getDate() % static_cast<int>(settings["session"]["savefrequency"].Integer()) == 0)
  164. {
  165. LOCPLINT->cb->save("Saves/" + prefix + "Autosave_" + boost::lexical_cast<std::string>(autosaveCount++ + 1));
  166. autosaveCount %= 5;
  167. }
  168. if (adventureInt->player != playerID)
  169. adventureInt->setPlayer(playerID);
  170. if (howManyPeople > 1) //hot seat message
  171. {
  172. adventureInt->startHotSeatWait(playerID);
  173. makingTurn = true;
  174. std::string msg = CGI->generaltexth->allTexts[13];
  175. boost::replace_first(msg, "%s", cb->getStartInfo()->playerInfos.find(playerID)->second.name);
  176. std::vector<CComponent*> cmp;
  177. cmp.push_back(new CComponent(CComponent::flag, playerID.getNum(), 0));
  178. showInfoDialog(msg, cmp);
  179. }
  180. else
  181. {
  182. makingTurn = true;
  183. adventureInt->startTurn();
  184. }
  185. }
  186. acceptTurn();
  187. }
  188. STRONG_INLINE void subRect(const int & x, const int & y, const int & z, const SDL_Rect & r, const ObjectInstanceID & hid)
  189. {
  190. TerrainTile2 & hlp = CGI->mh->ttiles[x][y][z];
  191. for (auto & elem : hlp.objects)
  192. if (elem.obj && elem.obj->id == hid)
  193. {
  194. elem.rect = r;
  195. return;
  196. }
  197. }
  198. STRONG_INLINE void delObjRect(const int & x, const int & y, const int & z, const ObjectInstanceID & hid)
  199. {
  200. TerrainTile2 & hlp = CGI->mh->ttiles[x][y][z];
  201. for (int h=0; h<hlp.objects.size(); ++h)
  202. if (hlp.objects[h].obj && hlp.objects[h].obj->id == hid)
  203. {
  204. hlp.objects.erase(hlp.objects.begin()+h);
  205. return;
  206. }
  207. }
  208. void CPlayerInterface::heroMoved(const TryMoveHero & details)
  209. {
  210. EVENT_HANDLER_CALLED_BY_CLIENT;
  211. waitWhileDialog();
  212. if (LOCPLINT != this)
  213. return;
  214. if(settings["session"]["spectate"].Bool() && settings["session"]["spectate-ignore-hero"].Bool())
  215. return;
  216. const CGHeroInstance * hero = cb->getHero(details.id); //object representing this hero
  217. int3 hp = details.start;
  218. if (!hero)
  219. {
  220. //AI hero left the visible area (we can't obtain info)
  221. //TODO very evil workaround -> retrieve pointer to hero so we could animate it
  222. // TODO -> we should not need full CGHeroInstance structure to display animation or it should not be handled by playerint (but by the client itself)
  223. const TerrainTile2 &tile = CGI->mh->ttiles[hp.x-1][hp.y][hp.z];
  224. for (auto & elem : tile.objects)
  225. if (elem.obj && elem.obj->id == details.id)
  226. hero = dynamic_cast<const CGHeroInstance *>(elem.obj);
  227. if (!hero) //still nothing...
  228. return;
  229. }
  230. bool directlyAttackingCreature =
  231. details.attackedFrom
  232. && adventureInt->terrain.currentPath //in case if movement has been canceled in the meantime and path was already erased
  233. && adventureInt->terrain.currentPath->nodes.size() == 3;//FIXME should be 2 but works nevertheless...
  234. if (makingTurn && hero->tempOwner == playerID) //we are moving our hero - we may need to update assigned path
  235. {
  236. //We may need to change music - select new track, music handler will change it if needed
  237. CCS->musich->playMusicFromSet("terrain", LOCPLINT->cb->getTile(hero->visitablePos())->terType, true);
  238. if (details.result == TryMoveHero::TELEPORTATION)
  239. {
  240. if (adventureInt->terrain.currentPath)
  241. {
  242. assert(adventureInt->terrain.currentPath->nodes.size() >= 2);
  243. std::vector<CGPathNode>::const_iterator nodesIt = adventureInt->terrain.currentPath->nodes.end() - 1;
  244. if ((nodesIt)->coord == CGHeroInstance::convertPosition(details.start, false)
  245. && (nodesIt-1)->coord == CGHeroInstance::convertPosition(details.end, false))
  246. {
  247. //path was between entrance and exit of teleport -> OK, erase node as usual
  248. removeLastNodeFromPath(hero);
  249. }
  250. else
  251. {
  252. //teleport was not along current path, it'll now be invalid (hero is somewhere else)
  253. eraseCurrentPathOf(hero);
  254. }
  255. }
  256. adventureInt->centerOn(hero, true); //actualizing screen pos
  257. adventureInt->minimap.redraw();
  258. adventureInt->heroList.update(hero);
  259. return; //teleport - no fancy moving animation
  260. //TODO: smooth disappear / appear effect
  261. }
  262. if (hero->pos != details.end //hero didn't change tile but visit succeeded
  263. || directlyAttackingCreature) // or creature was attacked from endangering tile.
  264. {
  265. eraseCurrentPathOf(hero, false);
  266. }
  267. else if (adventureInt->terrain.currentPath && hero->pos == details.end) //&& hero is moving
  268. {
  269. if (details.start != details.end) //so we don't touch path when revisiting with spacebar
  270. removeLastNodeFromPath(hero);
  271. }
  272. }
  273. if (details.result != TryMoveHero::SUCCESS) //hero failed to move
  274. {
  275. hero->isStanding = true;
  276. stillMoveHero.setn(STOP_MOVE);
  277. GH.totalRedraw();
  278. adventureInt->heroList.update(hero);
  279. return;
  280. }
  281. ui32 speed;
  282. if(settings["session"]["spectate"].Bool())
  283. {
  284. if(!settings["session"]["spectate-hero-speed"].isNull())
  285. speed = settings["session"]["spectate-hero-speed"].Integer();
  286. }
  287. else if (makingTurn) // our turn, our hero moves
  288. speed = settings["adventure"]["heroSpeed"].Float();
  289. else
  290. speed = settings["adventure"]["enemySpeed"].Float();
  291. if (speed == 0)
  292. {
  293. //FIXME: is this a proper solution?
  294. CGI->mh->hideObject(hero);
  295. CGI->mh->printObject(hero);
  296. return; // no animation
  297. }
  298. adventureInt->centerOn(hero); //actualizing screen pos
  299. adventureInt->minimap.redraw();
  300. adventureInt->heroList.redraw();
  301. initMovement(details, hero, hp);
  302. //first initializing done
  303. GH.mainFPSmng->framerateDelay(); // after first move
  304. //main moving
  305. for (int i=1; i<32; i+=2*speed)
  306. {
  307. movementPxStep(details, i, hp, hero);
  308. #ifndef VCMI_ANDROID
  309. // currently android doesn't seem to be able to handle all these full redraws here, so let's disable it so at least it looks less choppy;
  310. // most likely this is connected with the way that this manual animation+framerate handling is solved
  311. adventureInt->updateScreen = true;
  312. #endif
  313. adventureInt->show(screen);
  314. {
  315. //evil returns here ...
  316. //todo: get rid of it
  317. logGlobal->traceStream() << "before [un]locks in " << __FUNCTION__;
  318. auto unlockPim = vstd::makeUnlockGuard(*pim); //let frame to be rendered
  319. GH.mainFPSmng->framerateDelay(); //for animation purposes
  320. logGlobal->traceStream() << "after [un]locks in " << __FUNCTION__;
  321. }
  322. //CSDL_Ext::update(screen);
  323. } //for (int i=1; i<32; i+=4)
  324. //main moving done
  325. //finishing move
  326. finishMovement(details, hp, hero);
  327. hero->isStanding = true;
  328. //move finished
  329. adventureInt->minimap.redraw();
  330. adventureInt->heroList.update(hero);
  331. //check if user cancelled movement
  332. {
  333. boost::unique_lock<boost::mutex> un(eventsM);
  334. while(!events.empty())
  335. {
  336. SDL_Event ev = events.front();
  337. events.pop();
  338. switch(ev.type)
  339. {
  340. case SDL_MOUSEBUTTONDOWN:
  341. stillMoveHero.setn(STOP_MOVE);
  342. break;
  343. case SDL_KEYDOWN:
  344. if (ev.key.keysym.sym < SDLK_F1 || ev.key.keysym.sym > SDLK_F15)
  345. stillMoveHero.setn(STOP_MOVE);
  346. break;
  347. }
  348. }
  349. }
  350. if (stillMoveHero.get() == WAITING_MOVE)
  351. stillMoveHero.setn(DURING_MOVE);
  352. // Hero attacked creature directly, set direction to face it.
  353. if (directlyAttackingCreature) {
  354. // Get direction to attacker.
  355. int3 posOffset = *details.attackedFrom - details.end + int3(2, 1, 0);
  356. static const ui8 dirLookup[3][3] = {
  357. { 1, 2, 3 },
  358. { 8, 0, 4 },
  359. { 7, 6, 5 }
  360. };
  361. // FIXME: Avoid const_cast, make moveDir mutable in some other way?
  362. const_cast<CGHeroInstance *>(hero)->moveDir = dirLookup[posOffset.y][posOffset.x];
  363. }
  364. }
  365. void CPlayerInterface::heroKilled(const CGHeroInstance* hero)
  366. {
  367. EVENT_HANDLER_CALLED_BY_CLIENT;
  368. LOG_TRACE_PARAMS(logGlobal, "Hero %s killed handler for player %s", hero->name % playerID);
  369. const CArmedInstance *newSelection = nullptr;
  370. if (makingTurn)
  371. {
  372. //find new object for selection: either hero
  373. int next = adventureInt->getNextHeroIndex(vstd::find_pos(wanderingHeroes, hero));
  374. if (next >= 0)
  375. newSelection = wanderingHeroes[next];
  376. //or town
  377. if (!newSelection || newSelection == hero)
  378. {
  379. if (towns.empty())
  380. newSelection = nullptr;
  381. else
  382. newSelection = towns.front();
  383. }
  384. }
  385. wanderingHeroes -= hero;
  386. if (vstd::contains(paths, hero))
  387. paths.erase(hero);
  388. adventureInt->heroList.update(hero);
  389. if (makingTurn && newSelection)
  390. adventureInt->select(newSelection, true);
  391. else if (adventureInt->selection == hero)
  392. adventureInt->selection = nullptr;
  393. }
  394. void CPlayerInterface::heroCreated(const CGHeroInstance * hero)
  395. {
  396. EVENT_HANDLER_CALLED_BY_CLIENT;
  397. wanderingHeroes.push_back(hero);
  398. adventureInt->heroList.update(hero);
  399. }
  400. void CPlayerInterface::openTownWindow(const CGTownInstance * town)
  401. {
  402. if (castleInt)
  403. castleInt->close();
  404. castleInt = new CCastleInterface(town);
  405. GH.pushInt(castleInt);
  406. }
  407. int3 CPlayerInterface::repairScreenPos(int3 pos)
  408. {
  409. if (pos.x<-CGI->mh->frameW)
  410. pos.x = -CGI->mh->frameW;
  411. if (pos.y<-CGI->mh->frameH)
  412. pos.y = -CGI->mh->frameH;
  413. if (pos.x>CGI->mh->sizes.x - adventureInt->terrain.tilesw + CGI->mh->frameW)
  414. pos.x = CGI->mh->sizes.x - adventureInt->terrain.tilesw + CGI->mh->frameW;
  415. if (pos.y>CGI->mh->sizes.y - adventureInt->terrain.tilesh + CGI->mh->frameH)
  416. pos.y = CGI->mh->sizes.y - adventureInt->terrain.tilesh + CGI->mh->frameH;
  417. return pos;
  418. }
  419. void CPlayerInterface::activateForSpectator()
  420. {
  421. adventureInt->state = CAdvMapInt::INGAME;
  422. adventureInt->activate();
  423. adventureInt->minimap.activate();
  424. }
  425. void CPlayerInterface::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  426. {
  427. EVENT_HANDLER_CALLED_BY_CLIENT;
  428. if (which == 4)
  429. {
  430. if (CAltarWindow *ctw = dynamic_cast<CAltarWindow *>(GH.topInt()))
  431. ctw->setExpToLevel();
  432. }
  433. else if (which < GameConstants::PRIMARY_SKILLS) //no need to redraw infowin if this is experience (exp is treated as prim skill with id==4)
  434. updateInfo(hero);
  435. }
  436. void CPlayerInterface::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  437. {
  438. EVENT_HANDLER_CALLED_BY_CLIENT;
  439. CUniversityWindow* cuw = dynamic_cast<CUniversityWindow*>(GH.topInt());
  440. if (cuw) //university window is open
  441. {
  442. GH.totalRedraw();
  443. }
  444. }
  445. void CPlayerInterface::heroManaPointsChanged(const CGHeroInstance * hero)
  446. {
  447. EVENT_HANDLER_CALLED_BY_CLIENT;
  448. updateInfo(hero);
  449. if (makingTurn && hero->tempOwner == playerID)
  450. adventureInt->heroList.update(hero);
  451. }
  452. void CPlayerInterface::heroMovePointsChanged(const CGHeroInstance * hero)
  453. {
  454. EVENT_HANDLER_CALLED_BY_CLIENT;
  455. if (makingTurn && hero->tempOwner == playerID)
  456. adventureInt->heroList.update(hero);
  457. }
  458. void CPlayerInterface::receivedResource()
  459. {
  460. EVENT_HANDLER_CALLED_BY_CLIENT;
  461. if (CMarketplaceWindow *mw = dynamic_cast<CMarketplaceWindow *>(GH.topInt()))
  462. mw->resourceChanged();
  463. GH.totalRedraw();
  464. }
  465. void CPlayerInterface::heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill>& skills, QueryID queryID)
  466. {
  467. EVENT_HANDLER_CALLED_BY_CLIENT;
  468. waitWhileDialog();
  469. CCS->soundh->playSound(soundBase::heroNewLevel);
  470. CLevelWindow *lw = new CLevelWindow(hero,pskill,skills,
  471. [=](ui32 selection){ cb->selectionMade(selection, queryID); });
  472. GH.pushInt(lw);
  473. }
  474. void CPlayerInterface::commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  475. {
  476. EVENT_HANDLER_CALLED_BY_CLIENT;
  477. waitWhileDialog();
  478. CCS->soundh->playSound(soundBase::heroNewLevel);
  479. GH.pushInt(new CStackWindow(commander, skills, [=](ui32 selection)
  480. {
  481. cb->selectionMade(selection, queryID);
  482. }));
  483. }
  484. void CPlayerInterface::heroInGarrisonChange(const CGTownInstance *town)
  485. {
  486. EVENT_HANDLER_CALLED_BY_CLIENT;
  487. updateInfo(town);
  488. if (town->garrisonHero) //wandering hero moved to the garrison
  489. {
  490. CGI->mh->hideObject(town->garrisonHero);
  491. if (town->garrisonHero->tempOwner == playerID && vstd::contains(wanderingHeroes,town->garrisonHero)) // our hero
  492. wanderingHeroes -= town->garrisonHero;
  493. }
  494. if (town->visitingHero) //hero leaves garrison
  495. {
  496. CGI->mh->printObject(town->visitingHero);
  497. if (town->visitingHero->tempOwner == playerID && !vstd::contains(wanderingHeroes,town->visitingHero)) // our hero
  498. wanderingHeroes.push_back(town->visitingHero);
  499. }
  500. adventureInt->heroList.update();
  501. adventureInt->updateNextHero(nullptr);
  502. if (CCastleInterface *c = castleInt)
  503. {
  504. c->garr->selectSlot(nullptr);
  505. c->garr->setArmy(town->getUpperArmy(), 0);
  506. c->garr->setArmy(town->visitingHero, 1);
  507. c->garr->recreateSlots();
  508. c->heroes->update();
  509. }
  510. for (IShowActivatable *isa : GH.listInt)
  511. {
  512. CKingdomInterface *ki = dynamic_cast<CKingdomInterface*>(isa);
  513. if (ki)
  514. {
  515. ki->townChanged(town);
  516. ki->updateGarrisons();
  517. }
  518. }
  519. GH.totalRedraw();
  520. }
  521. void CPlayerInterface::heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town)
  522. {
  523. EVENT_HANDLER_CALLED_BY_CLIENT;
  524. if (hero->tempOwner != playerID )
  525. return;
  526. waitWhileDialog();
  527. openTownWindow(town);
  528. }
  529. void CPlayerInterface::garrisonsChanged(std::vector<const CGObjectInstance *> objs)
  530. {
  531. boost::unique_lock<boost::recursive_mutex> un(*pim);
  532. for (auto object : objs)
  533. updateInfo(object);
  534. for (auto & elem : GH.listInt)
  535. {
  536. CGarrisonHolder *cgh = dynamic_cast<CGarrisonHolder*>(elem);
  537. if (cgh)
  538. cgh->updateGarrisons();
  539. if (CTradeWindow *cmw = dynamic_cast<CTradeWindow*>(elem))
  540. {
  541. if (vstd::contains(objs, cmw->hero))
  542. cmw->garrisonChanged();
  543. }
  544. }
  545. GH.totalRedraw();
  546. }
  547. void CPlayerInterface::garrisonChanged( const CGObjectInstance * obj)
  548. {
  549. garrisonsChanged(std::vector<const CGObjectInstance *>(1, obj));
  550. }
  551. void CPlayerInterface::buildChanged(const CGTownInstance *town, BuildingID buildingID, int what) //what: 1 - built, 2 - demolished
  552. {
  553. EVENT_HANDLER_CALLED_BY_CLIENT;
  554. switch (buildingID)
  555. {
  556. case BuildingID::FORT: case BuildingID::CITADEL: case BuildingID::CASTLE:
  557. case BuildingID::VILLAGE_HALL: case BuildingID::TOWN_HALL: case BuildingID::CITY_HALL: case BuildingID::CAPITOL:
  558. case BuildingID::RESOURCE_SILO:
  559. updateInfo(town);
  560. break;
  561. }
  562. if (castleInt)
  563. {
  564. castleInt->townlist->update(town);
  565. if (castleInt->town == town)
  566. {
  567. switch(what)
  568. {
  569. case 1:
  570. CCS->soundh->playSound(soundBase::newBuilding);
  571. castleInt->addBuilding(buildingID);
  572. break;
  573. case 2:
  574. castleInt->removeBuilding(buildingID);
  575. break;
  576. }
  577. }
  578. }
  579. adventureInt->townList.update(town);
  580. }
  581. void CPlayerInterface::battleStartBefore(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2)
  582. {
  583. //Don't wait for dialogs when we are non-active hot-seat player
  584. if (LOCPLINT == this)
  585. waitForAllDialogs();
  586. }
  587. void CPlayerInterface::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  588. {
  589. EVENT_HANDLER_CALLED_BY_CLIENT;
  590. if (settings["adventure"]["quickCombat"].Bool())
  591. {
  592. autofightingAI = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
  593. autofightingAI->init(cb);
  594. autofightingAI->battleStart(army1, army2, int3(0,0,0), hero1, hero2, side);
  595. isAutoFightOn = true;
  596. cb->registerBattleInterface(autofightingAI);
  597. // Player shouldn't be able to move on adventure map if quick combat is going
  598. adventureInt->quickCombatLock();
  599. }
  600. //Don't wait for dialogs when we are non-active hot-seat player
  601. if (LOCPLINT == this)
  602. waitForAllDialogs();
  603. BATTLE_EVENT_POSSIBLE_RETURN;
  604. }
  605. void CPlayerInterface::battleStacksHealedRes(const std::vector<std::pair<ui32, ui32> > & healedStacks, bool lifeDrain, bool tentHeal, si32 lifeDrainFrom)
  606. {
  607. EVENT_HANDLER_CALLED_BY_CLIENT;
  608. BATTLE_EVENT_POSSIBLE_RETURN;
  609. for (auto & healedStack : healedStacks)
  610. {
  611. const CStack * healed = cb->battleGetStackByID(healedStack.first);
  612. if (battleInt->creAnims[healed->ID]->isDead())
  613. {
  614. //stack has been resurrected
  615. battleInt->creAnims[healed->ID]->setType(CCreatureAnim::HOLDING);
  616. }
  617. }
  618. if (lifeDrain)
  619. {
  620. const CStack *attacker = cb->battleGetStackByID(healedStacks[0].first, false);
  621. const CStack *defender = cb->battleGetStackByID(lifeDrainFrom, false);
  622. int textOff = 0;
  623. if (attacker)
  624. {
  625. battleInt->displayEffect(52, attacker->position); //TODO: transparency
  626. if (attacker->count > 1)
  627. {
  628. textOff += 1;
  629. }
  630. CCS->soundh->playSound(soundBase::DRAINLIF);
  631. //print info about life drain
  632. auto txt = boost::format (CGI->generaltexth->allTexts[361 + textOff]) % attacker->getCreature()->nameSing % healedStacks[0].second % defender->getCreature()->namePl;
  633. battleInt->console->addText(boost::to_string(txt));
  634. }
  635. }
  636. if (tentHeal)
  637. {
  638. std::string text = CGI->generaltexth->allTexts[414];
  639. boost::algorithm::replace_first(text, "%s", cb->battleGetStackByID(lifeDrainFrom, false)->getCreature()->nameSing);
  640. boost::algorithm::replace_first(text, "%s", cb->battleGetStackByID(healedStacks[0].first, false)->getCreature()->nameSing);
  641. boost::algorithm::replace_first(text, "%d", boost::lexical_cast<std::string>(healedStacks[0].second));
  642. battleInt->console->addText(text);
  643. }
  644. }
  645. void CPlayerInterface::battleNewStackAppeared(const CStack * stack)
  646. {
  647. EVENT_HANDLER_CALLED_BY_CLIENT;
  648. BATTLE_EVENT_POSSIBLE_RETURN;
  649. battleInt->newStack(stack);
  650. }
  651. void CPlayerInterface::battleObstaclesRemoved(const std::set<si32> & removedObstacles)
  652. {
  653. EVENT_HANDLER_CALLED_BY_CLIENT;
  654. BATTLE_EVENT_POSSIBLE_RETURN;
  655. //update accessible hexes
  656. battleInt->redrawBackgroundWithHexes(battleInt->activeStack);
  657. }
  658. void CPlayerInterface::battleCatapultAttacked(const CatapultAttack & ca)
  659. {
  660. EVENT_HANDLER_CALLED_BY_CLIENT;
  661. BATTLE_EVENT_POSSIBLE_RETURN;
  662. battleInt->stackIsCatapulting(ca);
  663. }
  664. void CPlayerInterface::battleStacksRemoved(const BattleStacksRemoved & bsr)
  665. {
  666. EVENT_HANDLER_CALLED_BY_CLIENT;
  667. BATTLE_EVENT_POSSIBLE_RETURN;
  668. for (auto & elem : bsr.stackIDs) //for each removed stack
  669. {
  670. battleInt->stackRemoved(elem);
  671. }
  672. }
  673. 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
  674. {
  675. EVENT_HANDLER_CALLED_BY_CLIENT;
  676. BATTLE_EVENT_POSSIBLE_RETURN;
  677. battleInt->newRound(round);
  678. }
  679. void CPlayerInterface::actionStarted(const BattleAction &action)
  680. {
  681. EVENT_HANDLER_CALLED_BY_CLIENT;
  682. BATTLE_EVENT_POSSIBLE_RETURN;
  683. curAction = new BattleAction(action);
  684. battleInt->startAction(curAction);
  685. }
  686. void CPlayerInterface::actionFinished(const BattleAction &action)
  687. {
  688. EVENT_HANDLER_CALLED_BY_CLIENT;
  689. BATTLE_EVENT_POSSIBLE_RETURN;
  690. battleInt->endAction(curAction);
  691. delete curAction;
  692. curAction = nullptr;
  693. }
  694. BattleAction CPlayerInterface::activeStack(const CStack * stack) //called when it's turn of that stack
  695. {
  696. THREAD_CREATED_BY_CLIENT;
  697. logGlobal->traceStream() << "Awaiting command for " << stack->nodeName();
  698. auto stackId = stack->ID;
  699. auto stackName = stack->nodeName();
  700. if (autofightingAI)
  701. {
  702. if (isAutoFightOn)
  703. {
  704. auto ret = autofightingAI->activeStack(stack);
  705. if (isAutoFightOn)
  706. {
  707. return ret;
  708. }
  709. }
  710. cb->unregisterBattleInterface(autofightingAI);
  711. autofightingAI.reset();
  712. }
  713. CBattleInterface *b = battleInt;
  714. if(CBattleInterface::givenCommand.get())
  715. {
  716. logGlobal->errorStream() << "Command buffer must be clean! (we don't want to use old command)";
  717. vstd::clear_pointer(CBattleInterface::givenCommand.data);
  718. }
  719. {
  720. boost::unique_lock<boost::recursive_mutex> un(*pim);
  721. b->stackActivated(stack);
  722. //Regeneration & mana drain go there
  723. }
  724. //wait till BattleInterface sets its command
  725. boost::unique_lock<boost::mutex> lock(CBattleInterface::givenCommand.mx);
  726. while(!CBattleInterface::givenCommand.data)
  727. {
  728. CBattleInterface::givenCommand.cond.wait(lock);
  729. if (!battleInt) //battle ended while we were waiting for movement (eg. because of spell)
  730. throw boost::thread_interrupted(); //will shut the thread peacefully
  731. }
  732. //tidy up
  733. BattleAction ret = *(CBattleInterface::givenCommand.data);
  734. vstd::clear_pointer(CBattleInterface::givenCommand.data);
  735. if (ret.actionType == Battle::CANCEL)
  736. {
  737. if (stackId != ret.stackNumber)
  738. logGlobal->error("Not current active stack action canceled");
  739. logGlobal->traceStream() << "Canceled command for " << stackName;
  740. }
  741. else
  742. logGlobal->traceStream() << "Giving command for " << stackName;
  743. return ret;
  744. }
  745. void CPlayerInterface::battleEnd(const BattleResult *br)
  746. {
  747. EVENT_HANDLER_CALLED_BY_CLIENT;
  748. if (isAutoFightOn)
  749. {
  750. isAutoFightOn = false;
  751. cb->unregisterBattleInterface(autofightingAI);
  752. autofightingAI.reset();
  753. adventureInt->quickCombatUnlock();
  754. if (!battleInt)
  755. {
  756. SDL_Rect temp_rect = genRect(561, 470, (screen->w - 800)/2 + 165, (screen->h - 600)/2 + 19);
  757. auto resWindow = new CBattleResultWindow(*br, temp_rect, *this);
  758. GH.pushInt(resWindow);
  759. // #1490 - during AI turn when quick combat is on, we need to display the message and wait for user to close it.
  760. // Otherwise NewTurn causes freeze.
  761. waitWhileDialog();
  762. return;
  763. }
  764. }
  765. BATTLE_EVENT_POSSIBLE_RETURN;
  766. battleInt->battleFinished(*br);
  767. }
  768. void CPlayerInterface::battleStackMoved(const CStack * stack, std::vector<BattleHex> dest, int distance)
  769. {
  770. EVENT_HANDLER_CALLED_BY_CLIENT;
  771. BATTLE_EVENT_POSSIBLE_RETURN;
  772. battleInt->stackMoved(stack, dest, distance);
  773. }
  774. void CPlayerInterface::battleSpellCast( const BattleSpellCast *sc )
  775. {
  776. EVENT_HANDLER_CALLED_BY_CLIENT;
  777. BATTLE_EVENT_POSSIBLE_RETURN;
  778. battleInt->spellCast(sc);
  779. }
  780. void CPlayerInterface::battleStacksEffectsSet( const SetStackEffect & sse )
  781. {
  782. EVENT_HANDLER_CALLED_BY_CLIENT;
  783. BATTLE_EVENT_POSSIBLE_RETURN;
  784. battleInt->battleStacksEffectsSet(sse);
  785. }
  786. void CPlayerInterface::battleTriggerEffect (const BattleTriggerEffect & bte)
  787. {
  788. EVENT_HANDLER_CALLED_BY_CLIENT;
  789. //TODO why is this different (no return on LOPLINT != this) ?
  790. RETURN_IF_QUICK_COMBAT;
  791. battleInt->battleTriggerEffect(bte);
  792. }
  793. void CPlayerInterface::battleStacksAttacked(const std::vector<BattleStackAttacked> & bsa)
  794. {
  795. EVENT_HANDLER_CALLED_BY_CLIENT;
  796. BATTLE_EVENT_POSSIBLE_RETURN;
  797. std::vector<StackAttackedInfo> arg;
  798. for (auto & elem : bsa)
  799. {
  800. const CStack *defender = cb->battleGetStackByID(elem.stackAttacked, false);
  801. const CStack *attacker = cb->battleGetStackByID(elem.attackerID, false);
  802. if (elem.isEffect())
  803. {
  804. if (defender && !elem.isSecondary())
  805. battleInt->displayEffect(elem.effect, defender->position);
  806. }
  807. if (elem.isSpell())
  808. {
  809. if (defender)
  810. battleInt->displaySpellEffect(elem.spellID, defender->position);
  811. }
  812. //FIXME: why action is deleted during enchanter cast?
  813. bool remoteAttack = false;
  814. if (LOCPLINT->curAction)
  815. remoteAttack |= LOCPLINT->curAction->actionType != Battle::WALK_AND_ATTACK;
  816. StackAttackedInfo to_put = {defender, elem.damageAmount, elem.killedAmount, attacker, remoteAttack, elem.killed(), elem.willRebirth(), elem.cloneKilled()};
  817. arg.push_back(to_put);
  818. }
  819. battleInt->stacksAreAttacked(arg);
  820. }
  821. void CPlayerInterface::battleAttack(const BattleAttack *ba)
  822. {
  823. EVENT_HANDLER_CALLED_BY_CLIENT;
  824. BATTLE_EVENT_POSSIBLE_RETURN;
  825. assert(curAction);
  826. if (ba->lucky()) //lucky hit
  827. {
  828. const CStack *stack = cb->battleGetStackByID(ba->stackAttacking);
  829. std::string hlp = CGI->generaltexth->allTexts[45];
  830. boost::algorithm::replace_first(hlp,"%s", (stack->count != 1) ? stack->getCreature()->namePl.c_str() : stack->getCreature()->nameSing.c_str());
  831. battleInt->console->addText(hlp);
  832. battleInt->displayEffect(18, stack->position);
  833. CCS->soundh->playSound(soundBase::GOODLUCK);
  834. }
  835. if (ba->unlucky()) //unlucky hit
  836. {
  837. const CStack *stack = cb->battleGetStackByID(ba->stackAttacking);
  838. std::string hlp = CGI->generaltexth->allTexts[44];
  839. boost::algorithm::replace_first(hlp,"%s", (stack->count != 1) ? stack->getCreature()->namePl.c_str() : stack->getCreature()->nameSing.c_str());
  840. battleInt->console->addText(hlp);
  841. battleInt->displayEffect(48, stack->position);
  842. CCS->soundh->playSound(soundBase::BADLUCK);
  843. }
  844. if (ba->deathBlow())
  845. {
  846. const CStack *stack = cb->battleGetStackByID(ba->stackAttacking);
  847. std::string hlp = CGI->generaltexth->allTexts[(stack->count != 1) ? 366 : 365];
  848. boost::algorithm::replace_first(hlp,"%s", (stack->count != 1) ? stack->getCreature()->namePl.c_str() : stack->getCreature()->nameSing.c_str());
  849. battleInt->console->addText(hlp);
  850. for (auto & elem : ba->bsa)
  851. {
  852. const CStack * attacked = cb->battleGetStackByID(elem.stackAttacked);
  853. battleInt->displayEffect(73, attacked->position);
  854. }
  855. CCS->soundh->playSound(soundBase::deathBlow);
  856. }
  857. battleInt->waitForAnims();
  858. const CStack * attacker = cb->battleGetStackByID(ba->stackAttacking);
  859. if (ba->shot())
  860. {
  861. for (auto & elem : ba->bsa)
  862. {
  863. if (!elem.isSecondary()) //display projectile only for primary target
  864. {
  865. const CStack * attacked = cb->battleGetStackByID(elem.stackAttacked);
  866. battleInt->stackAttacking(attacker, attacked->position, attacked, true);
  867. }
  868. }
  869. }
  870. else
  871. {
  872. int shift = 0;
  873. if (ba->counter() && BattleHex::mutualPosition(curAction->destinationTile, attacker->position) < 0)
  874. {
  875. int distp = BattleHex::getDistance(curAction->destinationTile + 1, attacker->position);
  876. int distm = BattleHex::getDistance(curAction->destinationTile - 1, attacker->position);
  877. if ( distp < distm )
  878. shift = 1;
  879. else
  880. shift = -1;
  881. }
  882. const CStack * attacked = cb->battleGetStackByID(ba->bsa.begin()->stackAttacked);
  883. battleInt->stackAttacking( attacker, ba->counter() ? curAction->destinationTile + shift : curAction->additionalInfo, attacked, false);
  884. }
  885. //battleInt->waitForAnims(); //FIXME: freeze
  886. if (ba->spellLike())
  887. {
  888. //display hit animation
  889. SpellID spellID = ba->spellID;
  890. battleInt->displaySpellHit(spellID,curAction->destinationTile);
  891. }
  892. }
  893. void CPlayerInterface::battleObstaclePlaced(const CObstacleInstance &obstacle)
  894. {
  895. EVENT_HANDLER_CALLED_BY_CLIENT;
  896. BATTLE_EVENT_POSSIBLE_RETURN;
  897. battleInt->obstaclePlaced(obstacle);
  898. }
  899. void CPlayerInterface::battleGateStateChanged(const EGateState state)
  900. {
  901. EVENT_HANDLER_CALLED_BY_CLIENT;
  902. BATTLE_EVENT_POSSIBLE_RETURN;
  903. battleInt->gateStateChanged(state);
  904. }
  905. void CPlayerInterface::yourTacticPhase(int distance)
  906. {
  907. THREAD_CREATED_BY_CLIENT;
  908. while(battleInt && battleInt->tacticsMode)
  909. boost::this_thread::sleep(boost::posix_time::millisec(1));
  910. }
  911. void CPlayerInterface::showComp(const Component &comp, std::string message)
  912. {
  913. EVENT_HANDLER_CALLED_BY_CLIENT;
  914. waitWhileDialog(); //Fix for mantis #98
  915. CCS->soundh->playSoundFromSet(CCS->soundh->pickupSounds);
  916. adventureInt->infoBar.showComponent(comp, message);
  917. }
  918. void CPlayerInterface::showInfoDialog(const std::string &text, const std::vector<Component*> &components, int soundID)
  919. {
  920. EVENT_HANDLER_CALLED_BY_CLIENT;
  921. if (settings["session"]["autoSkip"].Bool() && !LOCPLINT->shiftPressed())
  922. {
  923. return;
  924. }
  925. std::vector<CComponent*> intComps;
  926. for (auto & component : components)
  927. intComps.push_back(new CComponent(*component));
  928. showInfoDialog(text,intComps,soundID);
  929. }
  930. void CPlayerInterface::showInfoDialog(const std::string &text, CComponent * component)
  931. {
  932. std::vector<CComponent*> intComps;
  933. intComps.push_back(component);
  934. showInfoDialog(text, intComps, soundBase::sound_todo, true);
  935. }
  936. void CPlayerInterface::showInfoDialog(const std::string &text, const std::vector<CComponent*> & components, int soundID, bool delComps)
  937. {
  938. LOG_TRACE_PARAMS(logGlobal, "player=%s, text=%s, is LOCPLINT=%d", playerID % text % (this==LOCPLINT));
  939. waitWhileDialog();
  940. if (settings["session"]["autoSkip"].Bool() && !LOCPLINT->shiftPressed())
  941. {
  942. return;
  943. }
  944. CInfoWindow *temp = CInfoWindow::create(text, playerID, &components);
  945. temp->setDelComps(delComps);
  946. if (makingTurn && GH.listInt.size() && LOCPLINT == this)
  947. {
  948. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  949. showingDialog->set(true);
  950. stopMovement(); // interrupt movement to show dialog
  951. GH.pushInt(temp);
  952. }
  953. else
  954. {
  955. dialogs.push_back(temp);
  956. }
  957. }
  958. void CPlayerInterface::showInfoDialogAndWait(std::vector<Component> & components, const MetaString & text)
  959. {
  960. EVENT_HANDLER_CALLED_BY_CLIENT;
  961. std::vector<Component*> comps;
  962. for (auto & elem : components)
  963. {
  964. comps.push_back(&elem);
  965. }
  966. std::string str;
  967. text.toString(str);
  968. showInfoDialog(str,comps, 0);
  969. waitWhileDialog();
  970. }
  971. void CPlayerInterface::showYesNoDialog(const std::string &text, CFunctionList<void()> onYes, CFunctionList<void()> onNo, bool DelComps, const std::vector<CComponent*> & components)
  972. {
  973. boost::unique_lock<boost::recursive_mutex> un(*pim);
  974. stopMovement();
  975. LOCPLINT->showingDialog->setn(true);
  976. CInfoWindow::showYesNoDialog(text, &components, onYes, onNo, DelComps, playerID);
  977. }
  978. void CPlayerInterface::showOkDialog(std::vector<Component> & components, const MetaString & text, const std::function<void()> & onOk)
  979. {
  980. boost::unique_lock<boost::recursive_mutex> un(*pim);
  981. std::vector<Component*> comps;
  982. for (auto & elem : components)
  983. {
  984. comps.push_back(&elem);
  985. }
  986. std::string str;
  987. text.toString(str);
  988. stopMovement();
  989. showingDialog->setn(true);
  990. std::vector<CComponent*> intComps;
  991. for (auto & component : comps)
  992. intComps.push_back(new CComponent(*component));
  993. CInfoWindow::showOkDialog(str, &intComps, onOk, true, playerID);
  994. }
  995. void CPlayerInterface::showBlockingDialog( const std::string &text, const std::vector<Component> &components, QueryID askID, const int soundID, bool selection, bool cancel )
  996. {
  997. EVENT_HANDLER_CALLED_BY_CLIENT;
  998. waitWhileDialog();
  999. stopMovement();
  1000. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  1001. if (!selection && cancel) //simple yes/no dialog
  1002. {
  1003. std::vector<CComponent*> intComps;
  1004. for (auto & component : components)
  1005. intComps.push_back(new CComponent(component)); //will be deleted by close in window
  1006. showYesNoDialog(text, [=]{ cb->selectionMade(1, askID); }, [=]{ cb->selectionMade(0, askID); }, true, intComps);
  1007. }
  1008. else if (selection)
  1009. {
  1010. std::vector<CSelectableComponent*> intComps;
  1011. for (auto & component : components)
  1012. intComps.push_back(new CSelectableComponent(component)); //will be deleted by CSelWindow::close
  1013. std::vector<std::pair<std::string,CFunctionList<void()> > > pom;
  1014. pom.push_back(std::pair<std::string,CFunctionList<void()> >("IOKAY.DEF",0));
  1015. if (cancel)
  1016. {
  1017. pom.push_back(std::pair<std::string,CFunctionList<void()> >("ICANCEL.DEF",0));
  1018. }
  1019. int charperline = 35;
  1020. if (pom.size() > 1)
  1021. charperline = 50;
  1022. auto temp = new CSelWindow(text, playerID, charperline, intComps, pom, askID);
  1023. GH.pushInt(temp);
  1024. intComps[0]->clickLeft(true, false);
  1025. }
  1026. }
  1027. void CPlayerInterface::showTeleportDialog(TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  1028. {
  1029. EVENT_HANDLER_CALLED_BY_CLIENT;
  1030. int choosenExit = -1;
  1031. auto neededExit = std::make_pair(destinationTeleport, destinationTeleportPos);
  1032. if (destinationTeleport != ObjectInstanceID() && vstd::contains(exits, neededExit))
  1033. choosenExit = vstd::find_pos(exits, neededExit);
  1034. cb->selectionMade(choosenExit, askID);
  1035. }
  1036. void CPlayerInterface::tileRevealed(const std::unordered_set<int3, ShashInt3> &pos)
  1037. {
  1038. EVENT_HANDLER_CALLED_BY_CLIENT;
  1039. //FIXME: wait for dialog? Magi hut/eye would benefit from this but may break other areas
  1040. for (auto & po : pos)
  1041. adventureInt->minimap.showTile(po);
  1042. if (!pos.empty())
  1043. GH.totalRedraw();
  1044. }
  1045. void CPlayerInterface::tileHidden(const std::unordered_set<int3, ShashInt3> &pos)
  1046. {
  1047. EVENT_HANDLER_CALLED_BY_CLIENT;
  1048. for (auto & po : pos)
  1049. adventureInt->minimap.hideTile(po);
  1050. if (!pos.empty())
  1051. GH.totalRedraw();
  1052. }
  1053. void CPlayerInterface::openHeroWindow(const CGHeroInstance *hero)
  1054. {
  1055. boost::unique_lock<boost::recursive_mutex> un(*pim);
  1056. GH.pushInt(new CHeroWindow(hero));
  1057. }
  1058. /*
  1059. void CPlayerInterface::heroArtifactSetChanged(const CGHeroInstance*hero)
  1060. {
  1061. boost::unique_lock<boost::recursive_mutex> un(*pim);
  1062. if (adventureInt->heroWindow->curHero && adventureInt->heroWindow->curHero->id == hero->id) //hero window is opened
  1063. {
  1064. adventureInt->heroWindow->deactivate();
  1065. adventureInt->heroWindow->setHero(hero);
  1066. adventureInt->heroWindow->activate();
  1067. }
  1068. else if (CExchangeWindow* cew = dynamic_cast<CExchangeWindow*>(GH.topInt())) //exchange window is open
  1069. {
  1070. cew->deactivate();
  1071. for (int g=0; g<ARRAY_COUNT(cew->heroInst); ++g)
  1072. {
  1073. if (cew->heroInst[g]->id == hero->id)
  1074. {
  1075. cew->heroInst[g] = hero;
  1076. cew->artifs[g]->updateState = true;
  1077. cew->artifs[g]->setHero(hero);
  1078. cew->artifs[g]->updateState = false;
  1079. }
  1080. }
  1081. cew->prepareBackground();
  1082. cew->activate();
  1083. }
  1084. else if (CTradeWindow *caw = dynamic_cast<CTradeWindow*>(GH.topInt()))
  1085. {
  1086. if (caw->arts)
  1087. {
  1088. caw->deactivate();
  1089. caw->arts->updateState = true;
  1090. caw->arts->setHero(hero);
  1091. caw->arts->updateState = false;
  1092. caw->activate();
  1093. }
  1094. }
  1095. updateInfo(hero);
  1096. }*/
  1097. void CPlayerInterface::availableCreaturesChanged( const CGDwelling *town )
  1098. {
  1099. EVENT_HANDLER_CALLED_BY_CLIENT;
  1100. if (const CGTownInstance * townObj = dynamic_cast<const CGTownInstance*>(town))
  1101. {
  1102. CFortScreen *fs = dynamic_cast<CFortScreen*>(GH.topInt());
  1103. if (fs)
  1104. fs->creaturesChanged();
  1105. for (IShowActivatable *isa : GH.listInt)
  1106. {
  1107. CKingdomInterface *ki = dynamic_cast<CKingdomInterface*>(isa);
  1108. if (ki && townObj)
  1109. ki->townChanged(townObj);
  1110. }
  1111. }
  1112. else if (GH.listInt.size() && (town->ID == Obj::CREATURE_GENERATOR1
  1113. || town->ID == Obj::CREATURE_GENERATOR4 || town->ID == Obj::WAR_MACHINE_FACTORY))
  1114. {
  1115. CRecruitmentWindow *crw = dynamic_cast<CRecruitmentWindow*>(GH.topInt());
  1116. if (crw && crw->dwelling == town)
  1117. crw->availableCreaturesChanged();
  1118. }
  1119. }
  1120. void CPlayerInterface::heroBonusChanged( const CGHeroInstance *hero, const Bonus &bonus, bool gain )
  1121. {
  1122. EVENT_HANDLER_CALLED_BY_CLIENT;
  1123. if (bonus.type == Bonus::NONE)
  1124. return;
  1125. updateInfo(hero);
  1126. if ((bonus.type == Bonus::FLYING_MOVEMENT || bonus.type == Bonus::WATER_WALKING) && !gain)
  1127. {
  1128. //recalculate paths because hero has lost bonus influencing pathfinding
  1129. eraseCurrentPathOf(hero, false);
  1130. }
  1131. }
  1132. template <typename Handler> void CPlayerInterface::serializeTempl( Handler &h, const int version )
  1133. {
  1134. h & observerInDuelMode;
  1135. h & wanderingHeroes & towns & sleepingHeroes;
  1136. std::map<const CGHeroInstance *, int3> pathsMap; //hero -> dest
  1137. if (h.saving)
  1138. {
  1139. for (auto &p : paths)
  1140. {
  1141. if (p.second.nodes.size())
  1142. pathsMap[p.first] = p.second.endPos();
  1143. else
  1144. logGlobal->errorStream() << p.first->name << " has assigned an empty path! Ignoring it...";
  1145. }
  1146. h & pathsMap;
  1147. }
  1148. else
  1149. {
  1150. h & pathsMap;
  1151. if (cb)
  1152. for (auto &p : pathsMap)
  1153. {
  1154. CGPath path;
  1155. cb->getPathsInfo(p.first)->getPath(path, p.second);
  1156. paths[p.first] = path;
  1157. logGlobal->traceStream() << boost::format("Restored path for hero %s leading to %s with %d nodes")
  1158. % p.first->nodeName() % p.second % path.nodes.size();
  1159. }
  1160. }
  1161. h & spellbookSettings;
  1162. }
  1163. void CPlayerInterface::saveGame( BinarySerializer & h, const int version )
  1164. {
  1165. EVENT_HANDLER_CALLED_BY_CLIENT;
  1166. serializeTempl(h,version);
  1167. }
  1168. void CPlayerInterface::loadGame( BinaryDeserializer & h, const int version )
  1169. {
  1170. EVENT_HANDLER_CALLED_BY_CLIENT;
  1171. serializeTempl(h,version);
  1172. firstCall = -1;
  1173. }
  1174. void CPlayerInterface::moveHero( const CGHeroInstance *h, CGPath path )
  1175. {
  1176. logGlobal->traceStream() << __FUNCTION__;
  1177. if (!LOCPLINT->makingTurn)
  1178. return;
  1179. if (!h)
  1180. return; //can't find hero
  1181. //It shouldn't be possible to move hero with open dialog (or dialog waiting in bg)
  1182. if (showingDialog->get() || !dialogs.empty())
  1183. return;
  1184. setMovementStatus(true);
  1185. if (adventureInt && adventureInt->isHeroSleeping(h))
  1186. {
  1187. adventureInt->sleepWake->clickLeft(true, false);
  1188. adventureInt->sleepWake->clickLeft(false, true);
  1189. //could've just called
  1190. //adventureInt->fsleepWake();
  1191. //but no authentic button click/sound ;-)
  1192. }
  1193. boost::thread moveHeroTask(std::bind(&CPlayerInterface::doMoveHero,this,h,path));
  1194. }
  1195. bool CPlayerInterface::shiftPressed() const
  1196. {
  1197. return isShiftKeyDown();
  1198. }
  1199. bool CPlayerInterface::altPressed() const
  1200. {
  1201. return isAltKeyDown();
  1202. }
  1203. void CPlayerInterface::showGarrisonDialog( const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, QueryID queryID)
  1204. {
  1205. EVENT_HANDLER_CALLED_BY_CLIENT;
  1206. auto onEnd = [=]{ cb->selectionMade(0, queryID); };
  1207. if (stillMoveHero.get() == DURING_MOVE && adventureInt->terrain.currentPath && adventureInt->terrain.currentPath->nodes.size() > 1) //to ignore calls on passing through garrisons
  1208. {
  1209. onEnd();
  1210. return;
  1211. }
  1212. waitForAllDialogs();
  1213. auto cgw = new CGarrisonWindow(up,down,removableUnits);
  1214. cgw->quit->addCallback(onEnd);
  1215. GH.pushInt(cgw);
  1216. }
  1217. /**
  1218. * Shows the dialog that appears when right-clicking an artifact that can be assembled
  1219. * into a combinational one on an artifact screen. Does not require the combination of
  1220. * artifacts to be legal.
  1221. * @param artifactID ID of a constituent artifact.
  1222. * @param assembleTo ID of artifact to assemble a constituent into, not used when assemble
  1223. * is false.
  1224. * @param assemble True if the artifact is to be assembled, false if it is to be disassembled.
  1225. */
  1226. void CPlayerInterface::showArtifactAssemblyDialog (ui32 artifactID, ui32 assembleTo, bool assemble, CFunctionList<bool()> onYes, CFunctionList<bool()> onNo)
  1227. {
  1228. const CArtifact &artifact = *CGI->arth->artifacts[artifactID];
  1229. std::string text = artifact.Description();
  1230. text += "\n\n";
  1231. std::vector<CComponent*> scs;
  1232. if (assemble) {
  1233. const CArtifact &assembledArtifact = *CGI->arth->artifacts[assembleTo];
  1234. // You possess all of the components to...
  1235. text += boost::str(boost::format(CGI->generaltexth->allTexts[732]) % assembledArtifact.Name());
  1236. // Picture of assembled artifact at bottom.
  1237. auto sc = new CComponent(CComponent::artifact, assembledArtifact.id, 0);
  1238. //sc->description = assembledArtifact.Description();
  1239. //sc->subtitle = assembledArtifact.Name();
  1240. scs.push_back(sc);
  1241. } else {
  1242. // Do you wish to disassemble this artifact?
  1243. text += CGI->generaltexth->allTexts[733];
  1244. }
  1245. showYesNoDialog(text, onYes, onNo, true, scs);
  1246. }
  1247. void CPlayerInterface::requestRealized( PackageApplied *pa )
  1248. {
  1249. EVENT_HANDLER_CALLED_BY_CLIENT;
  1250. if (pa->packType == typeList.getTypeID<MoveHero>() && stillMoveHero.get() == DURING_MOVE
  1251. && destinationTeleport == ObjectInstanceID())
  1252. stillMoveHero.setn(CONTINUE_MOVE);
  1253. if (destinationTeleport != ObjectInstanceID()
  1254. && pa->packType == typeList.getTypeID<QueryReply>()
  1255. && stillMoveHero.get() == DURING_MOVE)
  1256. { // After teleportation via CGTeleport object is finished
  1257. destinationTeleport = ObjectInstanceID();
  1258. destinationTeleportPos = int3(-1);
  1259. stillMoveHero.setn(CONTINUE_MOVE);
  1260. }
  1261. }
  1262. void CPlayerInterface::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  1263. {
  1264. EVENT_HANDLER_CALLED_BY_CLIENT;
  1265. GH.pushInt(new CExchangeWindow(hero1, hero2, query));
  1266. }
  1267. void CPlayerInterface::objectPropertyChanged(const SetObjectProperty * sop)
  1268. {
  1269. EVENT_HANDLER_CALLED_BY_CLIENT;
  1270. //redraw minimap if owner changed
  1271. if (sop->what == ObjProperty::OWNER)
  1272. {
  1273. const CGObjectInstance * obj = cb->getObj(sop->id);
  1274. std::set<int3> pos = obj->getBlockedPos();
  1275. for (auto & po : pos)
  1276. {
  1277. if (cb->isVisible(po))
  1278. adventureInt->minimap.showTile(po);
  1279. }
  1280. if (obj->ID == Obj::TOWN)
  1281. {
  1282. if (obj->tempOwner == playerID)
  1283. towns.push_back(static_cast<const CGTownInstance *>(obj));
  1284. else
  1285. towns -= obj;
  1286. adventureInt->townList.update();
  1287. }
  1288. assert(cb->getTownsInfo().size() == towns.size());
  1289. }
  1290. }
  1291. void CPlayerInterface::initializeHeroTownList()
  1292. {
  1293. std::vector<const CGHeroInstance*> allHeroes = cb->getHeroesInfo();
  1294. /*
  1295. std::vector <const CGHeroInstance *> newWanderingHeroes;
  1296. //applying current heroes order to new heroes info
  1297. int j;
  1298. for (int i = 0; i < wanderingHeroes.size(); i++)
  1299. if ((j = vstd::find_pos(allHeroes, wanderingHeroes[i])) >= 0)
  1300. if (!allHeroes[j]->inTownGarrison)
  1301. {
  1302. newWanderingHeroes += allHeroes[j];
  1303. allHeroes -= allHeroes[j];
  1304. }
  1305. //all the rest of new heroes go the end of the list
  1306. wanderingHeroes.clear();
  1307. wanderingHeroes = newWanderingHeroes;
  1308. newWanderingHeroes.clear();*/
  1309. for (auto & allHeroe : allHeroes)
  1310. if (!allHeroe->inTownGarrison)
  1311. wanderingHeroes.push_back(allHeroe);
  1312. std::vector<const CGTownInstance*> allTowns = cb->getTownsInfo();
  1313. /*
  1314. std::vector<const CGTownInstance*> newTowns;
  1315. for (int i = 0; i < towns.size(); i++)
  1316. if ((j = vstd::find_pos(allTowns, towns[i])) >= 0)
  1317. {
  1318. newTowns += allTowns[j];
  1319. allTowns -= allTowns[j];
  1320. }
  1321. towns.clear();
  1322. towns = newTowns;
  1323. newTowns.clear();*/
  1324. for (auto & allTown : allTowns)
  1325. towns.push_back(allTown);
  1326. if (adventureInt)
  1327. adventureInt->updateNextHero(nullptr);
  1328. }
  1329. void CPlayerInterface::showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level)
  1330. {
  1331. EVENT_HANDLER_CALLED_BY_CLIENT;
  1332. waitWhileDialog();
  1333. auto recruitCb = [=](CreatureID id, int count){ LOCPLINT->cb->recruitCreatures(dwelling, dst, id, count, -1); };
  1334. CRecruitmentWindow *cr = new CRecruitmentWindow(dwelling, level, dst, recruitCb);
  1335. GH.pushInt(cr);
  1336. }
  1337. void CPlayerInterface::waitWhileDialog(bool unlockPim /*= true*/)
  1338. {
  1339. if (GH.amIGuiThread())
  1340. {
  1341. logGlobal->warnStream() << "Cannot wait for dialogs in gui thread (deadlock risk)!";
  1342. return;
  1343. }
  1344. auto unlock = vstd::makeUnlockGuardIf(*pim, unlockPim);
  1345. boost::unique_lock<boost::mutex> un(showingDialog->mx);
  1346. while(showingDialog->data)
  1347. showingDialog->cond.wait(un);
  1348. }
  1349. void CPlayerInterface::showShipyardDialog(const IShipyard *obj)
  1350. {
  1351. EVENT_HANDLER_CALLED_BY_CLIENT;
  1352. auto state = obj->shipyardStatus();
  1353. std::vector<si32> cost;
  1354. obj->getBoatCost(cost);
  1355. CShipyardWindow *csw = new CShipyardWindow(cost, state, obj->getBoatType(), [=]{ cb->buildBoat(obj); });
  1356. GH.pushInt(csw);
  1357. }
  1358. void CPlayerInterface::newObject( const CGObjectInstance * obj )
  1359. {
  1360. EVENT_HANDLER_CALLED_BY_CLIENT;
  1361. //we might have built a boat in shipyard in opened town screen
  1362. if (obj->ID == Obj::BOAT
  1363. && LOCPLINT->castleInt
  1364. && obj->pos-obj->getVisitableOffset() == LOCPLINT->castleInt->town->bestLocation())
  1365. {
  1366. CCS->soundh->playSound(soundBase::newBuilding);
  1367. LOCPLINT->castleInt->addBuilding(BuildingID::SHIP);
  1368. }
  1369. }
  1370. void CPlayerInterface::centerView (int3 pos, int focusTime)
  1371. {
  1372. EVENT_HANDLER_CALLED_BY_CLIENT;
  1373. waitWhileDialog();
  1374. CCS->curh->hide();
  1375. adventureInt->centerOn (pos);
  1376. if (focusTime)
  1377. {
  1378. GH.totalRedraw();
  1379. {
  1380. auto unlockPim = vstd::makeUnlockGuard(*pim);
  1381. IgnoreEvents ignore(*this);
  1382. SDL_Delay(focusTime);
  1383. }
  1384. }
  1385. CCS->curh->show();
  1386. }
  1387. void CPlayerInterface::objectRemoved( const CGObjectInstance *obj )
  1388. {
  1389. EVENT_HANDLER_CALLED_BY_CLIENT;
  1390. if (LOCPLINT->cb->getCurrentPlayer() == playerID) {
  1391. std::string handlerName = VLC->objtypeh->getObjectHandlerName(obj->ID);
  1392. if ((handlerName == "pickable") || (handlerName == "scholar") || (handlerName== "artifact") || (handlerName == "pandora")) {
  1393. waitWhileDialog();
  1394. CCS->soundh->playSoundFromSet(CCS->soundh->pickupSounds);
  1395. } else if ((handlerName == "monster") || (handlerName == "hero")) {
  1396. waitWhileDialog();
  1397. CCS->soundh->playSound(soundBase::KillFade);
  1398. }
  1399. }
  1400. if (obj->ID == Obj::HERO && obj->tempOwner == playerID)
  1401. {
  1402. const CGHeroInstance *h = static_cast<const CGHeroInstance*>(obj);
  1403. heroKilled(h);
  1404. }
  1405. }
  1406. bool CPlayerInterface::ctrlPressed() const
  1407. {
  1408. return isCtrlKeyDown();
  1409. }
  1410. const CArmedInstance * CPlayerInterface::getSelection()
  1411. {
  1412. return currentSelection;
  1413. }
  1414. void CPlayerInterface::setSelection(const CArmedInstance * obj)
  1415. {
  1416. currentSelection = obj;
  1417. }
  1418. void CPlayerInterface::update()
  1419. {
  1420. // Make sure that gamestate won't change when GUI objects may obtain its parts on event processing or drawing request
  1421. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  1422. // While mutexes were locked away we may be have stopped being the active interface
  1423. if (LOCPLINT != this)
  1424. return;
  1425. //if there are any waiting dialogs, show them
  1426. if ((howManyPeople <= 1 || makingTurn) && !dialogs.empty() && !showingDialog->get())
  1427. {
  1428. showingDialog->set(true);
  1429. GH.pushInt(dialogs.front());
  1430. dialogs.pop_front();
  1431. }
  1432. //in some conditions we may receive calls before selection is initialized - we must ignore them
  1433. if(adventureInt && GH.topInt() == adventureInt
  1434. && (!adventureInt->selection && !settings["session"]["spectate"].Bool()))
  1435. {
  1436. return;
  1437. }
  1438. // Handles mouse and key input
  1439. GH.updateTime();
  1440. GH.handleEvents();
  1441. #ifdef VCMI_ANDROID
  1442. if (adventureInt && !adventureInt->isActive() && (adventureInt->swipeTargetPosition.x >= 0 || adventureInt->swipeTargetPosition.y >= 0))
  1443. #else // !VCMI_ANDROID
  1444. if (adventureInt && !adventureInt->isActive() && adventureInt->scrollingDir) //player forces map scrolling though interface is disabled
  1445. #endif // !VCMI_ANDROID
  1446. GH.totalRedraw();
  1447. else
  1448. GH.simpleRedraw();
  1449. }
  1450. int CPlayerInterface::getLastIndex( std::string namePrefix)
  1451. {
  1452. using namespace boost::filesystem;
  1453. using namespace boost::algorithm;
  1454. path gamesDir = VCMIDirs::get().userSavePath();
  1455. std::map<std::time_t, int> dates; //save number => datestamp
  1456. const directory_iterator enddir;
  1457. if (!exists(gamesDir))
  1458. create_directory(gamesDir);
  1459. else
  1460. for (directory_iterator dir(gamesDir); dir != enddir; ++dir)
  1461. {
  1462. if (is_regular(dir->status()))
  1463. {
  1464. std::string name = dir->path().filename().string();
  1465. if (starts_with(name, namePrefix) && ends_with(name, ".vcgm1"))
  1466. {
  1467. char nr = name[namePrefix.size()];
  1468. if (std::isdigit(nr))
  1469. dates[last_write_time(dir->path())] = boost::lexical_cast<int>(nr);
  1470. }
  1471. }
  1472. }
  1473. if (!dates.empty())
  1474. return (--dates.end())->second; //return latest file number
  1475. return 0;
  1476. }
  1477. void CPlayerInterface::initMovement( const TryMoveHero &details, const CGHeroInstance * ho, const int3 &hp )
  1478. {
  1479. if (details.end.x+1 == details.start.x && details.end.y+1 == details.start.y) //tl
  1480. {
  1481. //ho->moveDir = 1;
  1482. ho->isStanding = false;
  1483. CGI->mh->ttiles[hp.x-3][hp.y-2][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, -31, -31)));
  1484. CGI->mh->ttiles[hp.x-2][hp.y-2][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 1, -31)));
  1485. CGI->mh->ttiles[hp.x-1][hp.y-2][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 33, -31)));
  1486. CGI->mh->ttiles[hp.x][hp.y-2][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 65, -31)));
  1487. CGI->mh->ttiles[hp.x-3][hp.y-1][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, -31, 1)));
  1488. subRect(hp.x-2, hp.y-1, hp.z, genRect(32, 32, 1, 1), ho->id);
  1489. subRect(hp.x-1, hp.y-1, hp.z, genRect(32, 32, 33, 1), ho->id);
  1490. subRect(hp.x, hp.y-1, hp.z, genRect(32, 32, 65, 1), ho->id);
  1491. CGI->mh->ttiles[hp.x-3][hp.y][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, -31, 33)));
  1492. subRect(hp.x-2, hp.y, hp.z, genRect(32, 32, 1, 33), ho->id);
  1493. subRect(hp.x-1, hp.y, hp.z, genRect(32, 32, 33, 33), ho->id);
  1494. subRect(hp.x, hp.y, hp.z, genRect(32, 32, 65, 33), ho->id);
  1495. std::stable_sort(CGI->mh->ttiles[hp.x-3][hp.y-2][hp.z].objects.begin(), CGI->mh->ttiles[hp.x-3][hp.y-2][hp.z].objects.end(), objectBlitOrderSorter);
  1496. std::stable_sort(CGI->mh->ttiles[hp.x-2][hp.y-2][hp.z].objects.begin(), CGI->mh->ttiles[hp.x-2][hp.y-2][hp.z].objects.end(), objectBlitOrderSorter);
  1497. std::stable_sort(CGI->mh->ttiles[hp.x-1][hp.y-2][hp.z].objects.begin(), CGI->mh->ttiles[hp.x-1][hp.y-2][hp.z].objects.end(), objectBlitOrderSorter);
  1498. std::stable_sort(CGI->mh->ttiles[hp.x][hp.y-2][hp.z].objects.begin(), CGI->mh->ttiles[hp.x][hp.y-2][hp.z].objects.end(), objectBlitOrderSorter);
  1499. std::stable_sort(CGI->mh->ttiles[hp.x-3][hp.y-1][hp.z].objects.begin(), CGI->mh->ttiles[hp.x-3][hp.y-1][hp.z].objects.end(), objectBlitOrderSorter);
  1500. std::stable_sort(CGI->mh->ttiles[hp.x-3][hp.y][hp.z].objects.begin(), CGI->mh->ttiles[hp.x-3][hp.y][hp.z].objects.end(), objectBlitOrderSorter);
  1501. }
  1502. else if (details.end.x == details.start.x && details.end.y+1 == details.start.y) //t
  1503. {
  1504. //ho->moveDir = 2;
  1505. ho->isStanding = false;
  1506. CGI->mh->ttiles[hp.x-2][hp.y-2][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 0, -31)));
  1507. CGI->mh->ttiles[hp.x-1][hp.y-2][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 32, -31)));
  1508. CGI->mh->ttiles[hp.x][hp.y-2][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 64, -31)));
  1509. subRect(hp.x-2, hp.y-1, hp.z, genRect(32, 32, 0, 1), ho->id);
  1510. subRect(hp.x-1, hp.y-1, hp.z, genRect(32, 32, 32, 1), ho->id);
  1511. subRect(hp.x, hp.y-1, hp.z, genRect(32, 32, 64, 1), ho->id);
  1512. subRect(hp.x-2, hp.y, hp.z, genRect(32, 32, 0, 33), ho->id);
  1513. subRect(hp.x-1, hp.y, hp.z, genRect(32, 32, 32, 33), ho->id);
  1514. subRect(hp.x, hp.y, hp.z, genRect(32, 32, 64, 33), ho->id);
  1515. std::stable_sort(CGI->mh->ttiles[hp.x-2][hp.y-2][hp.z].objects.begin(), CGI->mh->ttiles[hp.x-2][hp.y-2][hp.z].objects.end(), objectBlitOrderSorter);
  1516. std::stable_sort(CGI->mh->ttiles[hp.x-1][hp.y-2][hp.z].objects.begin(), CGI->mh->ttiles[hp.x-1][hp.y-2][hp.z].objects.end(), objectBlitOrderSorter);
  1517. std::stable_sort(CGI->mh->ttiles[hp.x][hp.y-2][hp.z].objects.begin(), CGI->mh->ttiles[hp.x][hp.y-2][hp.z].objects.end(), objectBlitOrderSorter);
  1518. }
  1519. else if (details.end.x-1 == details.start.x && details.end.y+1 == details.start.y) //tr
  1520. {
  1521. //ho->moveDir = 3;
  1522. ho->isStanding = false;
  1523. CGI->mh->ttiles[hp.x-2][hp.y-2][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, -1, -31)));
  1524. CGI->mh->ttiles[hp.x-1][hp.y-2][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 31, -31)));
  1525. CGI->mh->ttiles[hp.x][hp.y-2][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 63, -31)));
  1526. CGI->mh->ttiles[hp.x+1][hp.y-2][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 95, -31)));
  1527. subRect(hp.x-2, hp.y-1, hp.z, genRect(32, 32, -1, 1), ho->id);
  1528. subRect(hp.x-1, hp.y-1, hp.z, genRect(32, 32, 31, 1), ho->id);
  1529. subRect(hp.x, hp.y-1, hp.z, genRect(32, 32, 63, 1), ho->id);
  1530. CGI->mh->ttiles[hp.x+1][hp.y-1][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 95, 1)));
  1531. subRect(hp.x-2, hp.y, hp.z, genRect(32, 32, -1, 33), ho->id);
  1532. subRect(hp.x-1, hp.y, hp.z, genRect(32, 32, 31, 33), ho->id);
  1533. subRect(hp.x, hp.y, hp.z, genRect(32, 32, 63, 33), ho->id);
  1534. CGI->mh->ttiles[hp.x+1][hp.y][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 95, 33)));
  1535. std::stable_sort(CGI->mh->ttiles[hp.x-2][hp.y-2][hp.z].objects.begin(), CGI->mh->ttiles[hp.x-2][hp.y-2][hp.z].objects.end(), objectBlitOrderSorter);
  1536. std::stable_sort(CGI->mh->ttiles[hp.x-1][hp.y-2][hp.z].objects.begin(), CGI->mh->ttiles[hp.x-1][hp.y-2][hp.z].objects.end(), objectBlitOrderSorter);
  1537. std::stable_sort(CGI->mh->ttiles[hp.x][hp.y-2][hp.z].objects.begin(), CGI->mh->ttiles[hp.x][hp.y-2][hp.z].objects.end(), objectBlitOrderSorter);
  1538. std::stable_sort(CGI->mh->ttiles[hp.x+1][hp.y-2][hp.z].objects.begin(), CGI->mh->ttiles[hp.x+1][hp.y-2][hp.z].objects.end(), objectBlitOrderSorter);
  1539. std::stable_sort(CGI->mh->ttiles[hp.x+1][hp.y-1][hp.z].objects.begin(), CGI->mh->ttiles[hp.x+1][hp.y-1][hp.z].objects.end(), objectBlitOrderSorter);
  1540. std::stable_sort(CGI->mh->ttiles[hp.x+1][hp.y][hp.z].objects.begin(), CGI->mh->ttiles[hp.x+1][hp.y][hp.z].objects.end(), objectBlitOrderSorter);
  1541. }
  1542. else if (details.end.x-1 == details.start.x && details.end.y == details.start.y) //r
  1543. {
  1544. //ho->moveDir = 4;
  1545. ho->isStanding = false;
  1546. subRect(hp.x-2, hp.y-1, hp.z, genRect(32, 32, -1, 0), ho->id);
  1547. subRect(hp.x-1, hp.y-1, hp.z, genRect(32, 32, 31, 0), ho->id);
  1548. subRect(hp.x, hp.y-1, hp.z, genRect(32, 32, 63, 0), ho->id);
  1549. CGI->mh->ttiles[hp.x+1][hp.y-1][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 95, 0)));
  1550. subRect(hp.x-2, hp.y, hp.z, genRect(32, 32, -1, 32), ho->id);
  1551. subRect(hp.x-1, hp.y, hp.z, genRect(32, 32, 31, 32), ho->id);
  1552. subRect(hp.x, hp.y, hp.z, genRect(32, 32, 63, 32), ho->id);
  1553. CGI->mh->ttiles[hp.x+1][hp.y][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 95, 32)));
  1554. std::stable_sort(CGI->mh->ttiles[hp.x+1][hp.y-1][hp.z].objects.begin(), CGI->mh->ttiles[hp.x+1][hp.y-1][hp.z].objects.end(), objectBlitOrderSorter);
  1555. std::stable_sort(CGI->mh->ttiles[hp.x+1][hp.y][hp.z].objects.begin(), CGI->mh->ttiles[hp.x+1][hp.y][hp.z].objects.end(), objectBlitOrderSorter);
  1556. }
  1557. else if (details.end.x-1 == details.start.x && details.end.y-1 == details.start.y) //br
  1558. {
  1559. //ho->moveDir = 5;
  1560. ho->isStanding = false;
  1561. subRect(hp.x-2, hp.y-1, hp.z, genRect(32, 32, -1, -1), ho->id);
  1562. subRect(hp.x-1, hp.y-1, hp.z, genRect(32, 32, 31, -1), ho->id);
  1563. subRect(hp.x, hp.y-1, hp.z, genRect(32, 32, 63, -1), ho->id);
  1564. CGI->mh->ttiles[hp.x+1][hp.y-1][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 95, -1)));
  1565. subRect(hp.x-2, hp.y, hp.z, genRect(32, 32, -1, 31), ho->id);
  1566. subRect(hp.x-1, hp.y, hp.z, genRect(32, 32, 31, 31), ho->id);
  1567. subRect(hp.x, hp.y, hp.z, genRect(32, 32, 63, 31), ho->id);
  1568. CGI->mh->ttiles[hp.x+1][hp.y][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 95, 31)));
  1569. CGI->mh->ttiles[hp.x-2][hp.y+1][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, -1, 63)));
  1570. CGI->mh->ttiles[hp.x-1][hp.y+1][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 31, 63)));
  1571. CGI->mh->ttiles[hp.x][hp.y+1][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 63, 63)));
  1572. CGI->mh->ttiles[hp.x+1][hp.y+1][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 95, 63)));
  1573. std::stable_sort(CGI->mh->ttiles[hp.x+1][hp.y-1][hp.z].objects.begin(), CGI->mh->ttiles[hp.x+1][hp.y-1][hp.z].objects.end(), objectBlitOrderSorter);
  1574. std::stable_sort(CGI->mh->ttiles[hp.x+1][hp.y][hp.z].objects.begin(), CGI->mh->ttiles[hp.x+1][hp.y][hp.z].objects.end(), objectBlitOrderSorter);
  1575. std::stable_sort(CGI->mh->ttiles[hp.x-2][hp.y+1][hp.z].objects.begin(), CGI->mh->ttiles[hp.x-2][hp.y+1][hp.z].objects.end(), objectBlitOrderSorter);
  1576. std::stable_sort(CGI->mh->ttiles[hp.x-1][hp.y+1][hp.z].objects.begin(), CGI->mh->ttiles[hp.x-1][hp.y+1][hp.z].objects.end(), objectBlitOrderSorter);
  1577. std::stable_sort(CGI->mh->ttiles[hp.x][hp.y+1][hp.z].objects.begin(), CGI->mh->ttiles[hp.x][hp.y+1][hp.z].objects.end(), objectBlitOrderSorter);
  1578. std::stable_sort(CGI->mh->ttiles[hp.x+1][hp.y+1][hp.z].objects.begin(), CGI->mh->ttiles[hp.x+1][hp.y+1][hp.z].objects.end(), objectBlitOrderSorter);
  1579. }
  1580. else if (details.end.x == details.start.x && details.end.y-1 == details.start.y) //b
  1581. {
  1582. //ho->moveDir = 6;
  1583. ho->isStanding = false;
  1584. subRect(hp.x-2, hp.y-1, hp.z, genRect(32, 32, 0, -1), ho->id);
  1585. subRect(hp.x-1, hp.y-1, hp.z, genRect(32, 32, 32, -1), ho->id);
  1586. subRect(hp.x, hp.y-1, hp.z, genRect(32, 32, 64, -1), ho->id);
  1587. subRect(hp.x-2, hp.y, hp.z, genRect(32, 32, 0, 31), ho->id);
  1588. subRect(hp.x-1, hp.y, hp.z, genRect(32, 32, 32, 31), ho->id);
  1589. subRect(hp.x, hp.y, hp.z, genRect(32, 32, 64, 31), ho->id);
  1590. CGI->mh->ttiles[hp.x-2][hp.y+1][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 0, 63)));
  1591. CGI->mh->ttiles[hp.x-1][hp.y+1][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 32, 63)));
  1592. CGI->mh->ttiles[hp.x][hp.y+1][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 64, 63)));
  1593. std::stable_sort(CGI->mh->ttiles[hp.x-2][hp.y+1][hp.z].objects.begin(), CGI->mh->ttiles[hp.x-2][hp.y+1][hp.z].objects.end(), objectBlitOrderSorter);
  1594. std::stable_sort(CGI->mh->ttiles[hp.x-1][hp.y+1][hp.z].objects.begin(), CGI->mh->ttiles[hp.x-1][hp.y+1][hp.z].objects.end(), objectBlitOrderSorter);
  1595. std::stable_sort(CGI->mh->ttiles[hp.x][hp.y+1][hp.z].objects.begin(), CGI->mh->ttiles[hp.x][hp.y+1][hp.z].objects.end(), objectBlitOrderSorter);
  1596. }
  1597. else if (details.end.x+1 == details.start.x && details.end.y-1 == details.start.y) //bl
  1598. {
  1599. //ho->moveDir = 7;
  1600. ho->isStanding = false;
  1601. CGI->mh->ttiles[hp.x-3][hp.y-1][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, -31, -1)));
  1602. subRect(hp.x-2, hp.y-1, hp.z, genRect(32, 32, 1, -1), ho->id);
  1603. subRect(hp.x-1, hp.y-1, hp.z, genRect(32, 32, 33, -1), ho->id);
  1604. subRect(hp.x, hp.y-1, hp.z, genRect(32, 32, 65, -1), ho->id);
  1605. CGI->mh->ttiles[hp.x-3][hp.y][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, -31, 31)));
  1606. subRect(hp.x-2, hp.y, hp.z, genRect(32, 32, 1, 31), ho->id);
  1607. subRect(hp.x-1, hp.y, hp.z, genRect(32, 32, 33, 31), ho->id);
  1608. subRect(hp.x, hp.y, hp.z, genRect(32, 32, 65, 31), ho->id);
  1609. CGI->mh->ttiles[hp.x-3][hp.y+1][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, -31, 63)));
  1610. CGI->mh->ttiles[hp.x-2][hp.y+1][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 1, 63)));
  1611. CGI->mh->ttiles[hp.x-1][hp.y+1][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 33, 63)));
  1612. CGI->mh->ttiles[hp.x][hp.y+1][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, 65, 63)));
  1613. std::stable_sort(CGI->mh->ttiles[hp.x-3][hp.y-1][hp.z].objects.begin(), CGI->mh->ttiles[hp.x-3][hp.y-1][hp.z].objects.end(), objectBlitOrderSorter);
  1614. std::stable_sort(CGI->mh->ttiles[hp.x-3][hp.y][hp.z].objects.begin(), CGI->mh->ttiles[hp.x-3][hp.y][hp.z].objects.end(), objectBlitOrderSorter);
  1615. std::stable_sort(CGI->mh->ttiles[hp.x-3][hp.y+1][hp.z].objects.begin(), CGI->mh->ttiles[hp.x-3][hp.y+1][hp.z].objects.end(), objectBlitOrderSorter);
  1616. std::stable_sort(CGI->mh->ttiles[hp.x-2][hp.y+1][hp.z].objects.begin(), CGI->mh->ttiles[hp.x-2][hp.y+1][hp.z].objects.end(), objectBlitOrderSorter);
  1617. std::stable_sort(CGI->mh->ttiles[hp.x-1][hp.y+1][hp.z].objects.begin(), CGI->mh->ttiles[hp.x-1][hp.y+1][hp.z].objects.end(), objectBlitOrderSorter);
  1618. std::stable_sort(CGI->mh->ttiles[hp.x][hp.y+1][hp.z].objects.begin(), CGI->mh->ttiles[hp.x][hp.y+1][hp.z].objects.end(), objectBlitOrderSorter);
  1619. }
  1620. else if (details.end.x+1 == details.start.x && details.end.y == details.start.y) //l
  1621. {
  1622. //ho->moveDir = 8;
  1623. ho->isStanding = false;
  1624. CGI->mh->ttiles[hp.x-3][hp.y-1][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, -31, 0)));
  1625. subRect(hp.x-2, hp.y-1, hp.z, genRect(32, 32, 1, 0), ho->id);
  1626. subRect(hp.x-1, hp.y-1, hp.z, genRect(32, 32, 33, 0), ho->id);
  1627. subRect(hp.x, hp.y-1, hp.z, genRect(32, 32, 65, 0), ho->id);
  1628. CGI->mh->ttiles[hp.x-3][hp.y][hp.z].objects.push_back(TerrainTileObject(ho, genRect(32, 32, -31, 32)));
  1629. subRect(hp.x-2, hp.y, hp.z, genRect(32, 32, 1, 32), ho->id);
  1630. subRect(hp.x-1, hp.y, hp.z, genRect(32, 32, 33, 32), ho->id);
  1631. subRect(hp.x, hp.y, hp.z, genRect(32, 32, 65, 32), ho->id);
  1632. std::stable_sort(CGI->mh->ttiles[hp.x-3][hp.y-1][hp.z].objects.begin(), CGI->mh->ttiles[hp.x-3][hp.y-1][hp.z].objects.end(), objectBlitOrderSorter);
  1633. std::stable_sort(CGI->mh->ttiles[hp.x-3][hp.y][hp.z].objects.begin(), CGI->mh->ttiles[hp.x-3][hp.y][hp.z].objects.end(), objectBlitOrderSorter);
  1634. }
  1635. }
  1636. void CPlayerInterface::movementPxStep( const TryMoveHero &details, int i, const int3 &hp, const CGHeroInstance * ho )
  1637. {
  1638. if (details.end.x+1 == details.start.x && details.end.y+1 == details.start.y) //tl
  1639. {
  1640. //setting advmap shift
  1641. adventureInt->terrain.moveX = i-32;
  1642. adventureInt->terrain.moveY = i-32;
  1643. subRect(hp.x-3, hp.y-2, hp.z, genRect(32, 32, -31+i, -31+i), ho->id);
  1644. subRect(hp.x-2, hp.y-2, hp.z, genRect(32, 32, 1+i, -31+i), ho->id);
  1645. subRect(hp.x-1, hp.y-2, hp.z, genRect(32, 32, 33+i, -31+i), ho->id);
  1646. subRect(hp.x, hp.y-2, hp.z, genRect(32, 32, 65+i, -31+i), ho->id);
  1647. subRect(hp.x-3, hp.y-1, hp.z, genRect(32, 32, -31+i, 1+i), ho->id);
  1648. subRect(hp.x-2, hp.y-1, hp.z, genRect(32, 32, 1+i, 1+i), ho->id);
  1649. subRect(hp.x-1, hp.y-1, hp.z, genRect(32, 32, 33+i, 1+i), ho->id);
  1650. subRect(hp.x, hp.y-1, hp.z, genRect(32, 32, 65+i, 1+i), ho->id);
  1651. subRect(hp.x-3, hp.y, hp.z, genRect(32, 32, -31+i, 33+i), ho->id);
  1652. subRect(hp.x-2, hp.y, hp.z, genRect(32, 32, 1+i, 33+i), ho->id);
  1653. subRect(hp.x-1, hp.y, hp.z, genRect(32, 32, 33+i, 33+i), ho->id);
  1654. subRect(hp.x, hp.y, hp.z, genRect(32, 32, 65+i, 33+i), ho->id);
  1655. }
  1656. else if (details.end.x == details.start.x && details.end.y+1 == details.start.y) //t
  1657. {
  1658. //setting advmap shift
  1659. adventureInt->terrain.moveY = i-32;
  1660. subRect(hp.x-2, hp.y-2, hp.z, genRect(32, 32, 0, -31+i), ho->id);
  1661. subRect(hp.x-1, hp.y-2, hp.z, genRect(32, 32, 32, -31+i), ho->id);
  1662. subRect(hp.x, hp.y-2, hp.z, genRect(32, 32, 64, -31+i), ho->id);
  1663. subRect(hp.x-2, hp.y-1, hp.z, genRect(32, 32, 0, 1+i), ho->id);
  1664. subRect(hp.x-1, hp.y-1, hp.z, genRect(32, 32, 32, 1+i), ho->id);
  1665. subRect(hp.x, hp.y-1, hp.z, genRect(32, 32, 64, 1+i), ho->id);
  1666. subRect(hp.x-2, hp.y, hp.z, genRect(32, 32, 0, 33+i), ho->id);
  1667. subRect(hp.x-1, hp.y, hp.z, genRect(32, 32, 32, 33+i), ho->id);
  1668. subRect(hp.x, hp.y, hp.z, genRect(32, 32, 64, 33+i), ho->id);
  1669. }
  1670. else if (details.end.x-1 == details.start.x && details.end.y+1 == details.start.y) //tr
  1671. {
  1672. //setting advmap shift
  1673. adventureInt->terrain.moveX = -i+32;
  1674. adventureInt->terrain.moveY = i-32;
  1675. subRect(hp.x-2, hp.y-2, hp.z, genRect(32, 32, -1-i, -31+i), ho->id);
  1676. subRect(hp.x-1, hp.y-2, hp.z, genRect(32, 32, 31-i, -31+i), ho->id);
  1677. subRect(hp.x, hp.y-2, hp.z, genRect(32, 32, 63-i, -31+i), ho->id);
  1678. subRect(hp.x+1, hp.y-2, hp.z, genRect(32, 32, 95-i, -31+i), ho->id);
  1679. subRect(hp.x-2, hp.y-1, hp.z, genRect(32, 32, -1-i, 1+i), ho->id);
  1680. subRect(hp.x-1, hp.y-1, hp.z, genRect(32, 32, 31-i, 1+i), ho->id);
  1681. subRect(hp.x, hp.y-1, hp.z, genRect(32, 32, 63-i, 1+i), ho->id);
  1682. subRect(hp.x+1, hp.y-1, hp.z, genRect(32, 32, 95-i, 1+i), ho->id);
  1683. subRect(hp.x-2, hp.y, hp.z, genRect(32, 32, -1-i, 33+i), ho->id);
  1684. subRect(hp.x-1, hp.y, hp.z, genRect(32, 32, 31-i, 33+i), ho->id);
  1685. subRect(hp.x, hp.y, hp.z, genRect(32, 32, 63-i, 33+i), ho->id);
  1686. subRect(hp.x+1, hp.y, hp.z, genRect(32, 32, 95-i, 33+i), ho->id);
  1687. }
  1688. else if (details.end.x-1 == details.start.x && details.end.y == details.start.y) //r
  1689. {
  1690. //setting advmap shift
  1691. adventureInt->terrain.moveX = -i+32;
  1692. subRect(hp.x-2, hp.y-1, hp.z, genRect(32, 32, -1-i, 0), ho->id);
  1693. subRect(hp.x-1, hp.y-1, hp.z, genRect(32, 32, 31-i, 0), ho->id);
  1694. subRect(hp.x, hp.y-1, hp.z, genRect(32, 32, 63-i, 0), ho->id);
  1695. subRect(hp.x+1, hp.y-1, hp.z, genRect(32, 32, 95-i, 0), ho->id);
  1696. subRect(hp.x-2, hp.y, hp.z, genRect(32, 32, -1-i, 32), ho->id);
  1697. subRect(hp.x-1, hp.y, hp.z, genRect(32, 32, 31-i, 32), ho->id);
  1698. subRect(hp.x, hp.y, hp.z, genRect(32, 32, 63-i, 32), ho->id);
  1699. subRect(hp.x+1, hp.y, hp.z, genRect(32, 32, 95-i, 32), ho->id);
  1700. }
  1701. else if (details.end.x-1 == details.start.x && details.end.y-1 == details.start.y) //br
  1702. {
  1703. //setting advmap shift
  1704. adventureInt->terrain.moveX = -i+32;
  1705. adventureInt->terrain.moveY = -i+32;
  1706. subRect(hp.x-2, hp.y-1, hp.z, genRect(32, 32, -1-i, -1-i), ho->id);
  1707. subRect(hp.x-1, hp.y-1, hp.z, genRect(32, 32, 31-i, -1-i), ho->id);
  1708. subRect(hp.x, hp.y-1, hp.z, genRect(32, 32, 63-i, -1-i), ho->id);
  1709. subRect(hp.x+1, hp.y-1, hp.z, genRect(32, 32, 95-i, -1-i), ho->id);
  1710. subRect(hp.x-2, hp.y, hp.z, genRect(32, 32, -1-i, 31-i), ho->id);
  1711. subRect(hp.x-1, hp.y, hp.z, genRect(32, 32, 31-i, 31-i), ho->id);
  1712. subRect(hp.x, hp.y, hp.z, genRect(32, 32, 63-i, 31-i), ho->id);
  1713. subRect(hp.x+1, hp.y, hp.z, genRect(32, 32, 95-i, 31-i), ho->id);
  1714. subRect(hp.x-2, hp.y+1, hp.z, genRect(32, 32, -1-i, 63-i), ho->id);
  1715. subRect(hp.x-1, hp.y+1, hp.z, genRect(32, 32, 31-i, 63-i), ho->id);
  1716. subRect(hp.x, hp.y+1, hp.z, genRect(32, 32, 63-i, 63-i), ho->id);
  1717. subRect(hp.x+1, hp.y+1, hp.z, genRect(32, 32, 95-i, 63-i), ho->id);
  1718. }
  1719. else if (details.end.x == details.start.x && details.end.y-1 == details.start.y) //b
  1720. {
  1721. //setting advmap shift
  1722. adventureInt->terrain.moveY = -i+32;
  1723. subRect(hp.x-2, hp.y-1, hp.z, genRect(32, 32, 0, -1-i), ho->id);
  1724. subRect(hp.x-1, hp.y-1, hp.z, genRect(32, 32, 32, -1-i), ho->id);
  1725. subRect(hp.x, hp.y-1, hp.z, genRect(32, 32, 64, -1-i), ho->id);
  1726. subRect(hp.x-2, hp.y, hp.z, genRect(32, 32, 0, 31-i), ho->id);
  1727. subRect(hp.x-1, hp.y, hp.z, genRect(32, 32, 32, 31-i), ho->id);
  1728. subRect(hp.x, hp.y, hp.z, genRect(32, 32, 64, 31-i), ho->id);
  1729. subRect(hp.x-2, hp.y+1, hp.z, genRect(32, 32, 0, 63-i), ho->id);
  1730. subRect(hp.x-1, hp.y+1, hp.z, genRect(32, 32, 32, 63-i), ho->id);
  1731. subRect(hp.x, hp.y+1, hp.z, genRect(32, 32, 64, 63-i), ho->id);
  1732. }
  1733. else if (details.end.x+1 == details.start.x && details.end.y-1 == details.start.y) //bl
  1734. {
  1735. //setting advmap shift
  1736. adventureInt->terrain.moveX = i-32;
  1737. adventureInt->terrain.moveY = -i+32;
  1738. subRect(hp.x-3, hp.y-1, hp.z, genRect(32, 32, -31+i, -1-i), ho->id);
  1739. subRect(hp.x-2, hp.y-1, hp.z, genRect(32, 32, 1+i, -1-i), ho->id);
  1740. subRect(hp.x-1, hp.y-1, hp.z, genRect(32, 32, 33+i, -1-i), ho->id);
  1741. subRect(hp.x, hp.y-1, hp.z, genRect(32, 32, 65+i, -1-i), ho->id);
  1742. subRect(hp.x-3, hp.y, hp.z, genRect(32, 32, -31+i, 31-i), ho->id);
  1743. subRect(hp.x-2, hp.y, hp.z, genRect(32, 32, 1+i, 31-i), ho->id);
  1744. subRect(hp.x-1, hp.y, hp.z, genRect(32, 32, 33+i, 31-i), ho->id);
  1745. subRect(hp.x, hp.y, hp.z, genRect(32, 32, 65+i, 31-i), ho->id);
  1746. subRect(hp.x-3, hp.y+1, hp.z, genRect(32, 32, -31+i, 63-i), ho->id);
  1747. subRect(hp.x-2, hp.y+1, hp.z, genRect(32, 32, 1+i, 63-i), ho->id);
  1748. subRect(hp.x-1, hp.y+1, hp.z, genRect(32, 32, 33+i, 63-i), ho->id);
  1749. subRect(hp.x, hp.y+1, hp.z, genRect(32, 32, 65+i, 63-i), ho->id);
  1750. }
  1751. else if (details.end.x+1 == details.start.x && details.end.y == details.start.y) //l
  1752. {
  1753. //setting advmap shift
  1754. adventureInt->terrain.moveX = i-32;
  1755. subRect(hp.x-3, hp.y-1, hp.z, genRect(32, 32, -31+i, 0), ho->id);
  1756. subRect(hp.x-2, hp.y-1, hp.z, genRect(32, 32, 1+i, 0), ho->id);
  1757. subRect(hp.x-1, hp.y-1, hp.z, genRect(32, 32, 33+i, 0), ho->id);
  1758. subRect(hp.x, hp.y-1, hp.z, genRect(32, 32, 65+i, 0), ho->id);
  1759. subRect(hp.x-3, hp.y, hp.z, genRect(32, 32, -31+i, 32), ho->id);
  1760. subRect(hp.x-2, hp.y, hp.z, genRect(32, 32, 1+i, 32), ho->id);
  1761. subRect(hp.x-1, hp.y, hp.z, genRect(32, 32, 33+i, 32), ho->id);
  1762. subRect(hp.x, hp.y, hp.z, genRect(32, 32, 65+i, 32), ho->id);
  1763. }
  1764. }
  1765. void CPlayerInterface::finishMovement( const TryMoveHero &details, const int3 &hp, const CGHeroInstance * ho )
  1766. {
  1767. adventureInt->terrain.moveX = adventureInt->terrain.moveY = 0;
  1768. if (details.end.x+1 == details.start.x && details.end.y+1 == details.start.y) //tl
  1769. {
  1770. delObjRect(hp.x, hp.y-2, hp.z, ho->id);
  1771. delObjRect(hp.x, hp.y-1, hp.z, ho->id);
  1772. delObjRect(hp.x, hp.y, hp.z, ho->id);
  1773. delObjRect(hp.x-1, hp.y, hp.z, ho->id);
  1774. delObjRect(hp.x-2, hp.y, hp.z, ho->id);
  1775. delObjRect(hp.x-3, hp.y, hp.z, ho->id);
  1776. }
  1777. else if (details.end.x == details.start.x && details.end.y+1 == details.start.y) //t
  1778. {
  1779. delObjRect(hp.x, hp.y, hp.z, ho->id);
  1780. delObjRect(hp.x-1, hp.y, hp.z, ho->id);
  1781. delObjRect(hp.x-2, hp.y, hp.z, ho->id);
  1782. }
  1783. else if (details.end.x-1 == details.start.x && details.end.y+1 == details.start.y) //tr
  1784. {
  1785. delObjRect(hp.x-2, hp.y-2, hp.z, ho->id);
  1786. delObjRect(hp.x-2, hp.y-1, hp.z, ho->id);
  1787. delObjRect(hp.x+1, hp.y, hp.z, ho->id);
  1788. delObjRect(hp.x, hp.y, hp.z, ho->id);
  1789. delObjRect(hp.x-1, hp.y, hp.z, ho->id);
  1790. delObjRect(hp.x-2, hp.y, hp.z, ho->id);
  1791. }
  1792. else if (details.end.x-1 == details.start.x && details.end.y == details.start.y) //r
  1793. {
  1794. delObjRect(hp.x-2, hp.y-1, hp.z, ho->id);
  1795. delObjRect(hp.x-2, hp.y, hp.z, ho->id);
  1796. }
  1797. else if (details.end.x-1 == details.start.x && details.end.y-1 == details.start.y) //br
  1798. {
  1799. delObjRect(hp.x-2, hp.y+1, hp.z, ho->id);
  1800. delObjRect(hp.x-2, hp.y, hp.z, ho->id);
  1801. delObjRect(hp.x+1, hp.y-1, hp.z, ho->id);
  1802. delObjRect(hp.x, hp.y-1, hp.z, ho->id);
  1803. delObjRect(hp.x-1, hp.y-1, hp.z, ho->id);
  1804. delObjRect(hp.x-2, hp.y-1, hp.z, ho->id);
  1805. }
  1806. else if (details.end.x == details.start.x && details.end.y-1 == details.start.y) //b
  1807. {
  1808. delObjRect(hp.x, hp.y-1, hp.z, ho->id);
  1809. delObjRect(hp.x-1, hp.y-1, hp.z, ho->id);
  1810. delObjRect(hp.x-2, hp.y-1, hp.z, ho->id);
  1811. }
  1812. else if (details.end.x+1 == details.start.x && details.end.y-1 == details.start.y) //bl
  1813. {
  1814. delObjRect(hp.x, hp.y-1, hp.z, ho->id);
  1815. delObjRect(hp.x-1, hp.y-1, hp.z, ho->id);
  1816. delObjRect(hp.x-2, hp.y-1, hp.z, ho->id);
  1817. delObjRect(hp.x-3, hp.y-1, hp.z, ho->id);
  1818. delObjRect(hp.x, hp.y, hp.z, ho->id);
  1819. delObjRect(hp.x, hp.y+1, hp.z, ho->id);
  1820. }
  1821. else if (details.end.x+1 == details.start.x && details.end.y == details.start.y) //l
  1822. {
  1823. delObjRect(hp.x, hp.y-1, hp.z, ho->id);
  1824. delObjRect(hp.x, hp.y, hp.z, ho->id);
  1825. }
  1826. //restoring good rects
  1827. subRect(details.end.x-2, details.end.y-1, details.end.z, genRect(32, 32, 0, 0), ho->id);
  1828. subRect(details.end.x-1, details.end.y-1, details.end.z, genRect(32, 32, 32, 0), ho->id);
  1829. subRect(details.end.x, details.end.y-1, details.end.z, genRect(32, 32, 64, 0), ho->id);
  1830. subRect(details.end.x-2, details.end.y, details.end.z, genRect(32, 32, 0, 32), ho->id);
  1831. subRect(details.end.x-1, details.end.y, details.end.z, genRect(32, 32, 32, 32), ho->id);
  1832. subRect(details.end.x, details.end.y, details.end.z, genRect(32, 32, 64, 32), ho->id);
  1833. //restoring good order of objects
  1834. std::stable_sort(CGI->mh->ttiles[details.end.x-2][details.end.y-1][details.end.z].objects.begin(), CGI->mh->ttiles[details.end.x-2][details.end.y-1][details.end.z].objects.end(), objectBlitOrderSorter);
  1835. std::stable_sort(CGI->mh->ttiles[details.end.x-1][details.end.y-1][details.end.z].objects.begin(), CGI->mh->ttiles[details.end.x-1][details.end.y-1][details.end.z].objects.end(), objectBlitOrderSorter);
  1836. std::stable_sort(CGI->mh->ttiles[details.end.x][details.end.y-1][details.end.z].objects.begin(), CGI->mh->ttiles[details.end.x][details.end.y-1][details.end.z].objects.end(), objectBlitOrderSorter);
  1837. std::stable_sort(CGI->mh->ttiles[details.end.x-2][details.end.y][details.end.z].objects.begin(), CGI->mh->ttiles[details.end.x-2][details.end.y][details.end.z].objects.end(), objectBlitOrderSorter);
  1838. std::stable_sort(CGI->mh->ttiles[details.end.x-1][details.end.y][details.end.z].objects.begin(), CGI->mh->ttiles[details.end.x-1][details.end.y][details.end.z].objects.end(), objectBlitOrderSorter);
  1839. std::stable_sort(CGI->mh->ttiles[details.end.x][details.end.y][details.end.z].objects.begin(), CGI->mh->ttiles[details.end.x][details.end.y][details.end.z].objects.end(), objectBlitOrderSorter);
  1840. }
  1841. void CPlayerInterface::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult )
  1842. {
  1843. EVENT_HANDLER_CALLED_BY_CLIENT;
  1844. if (player == playerID)
  1845. {
  1846. if (victoryLossCheckResult.loss())
  1847. showInfoDialog(CGI->generaltexth->allTexts[95]);
  1848. if (LOCPLINT == this)
  1849. {
  1850. GH.curInt = this; //waiting for dialogs requires this to get events
  1851. waitForAllDialogs(); //wait till all dialogs are displayed and closed
  1852. }
  1853. --howManyPeople;
  1854. if(howManyPeople == 0 && !settings["session"]["spectate"].Bool()) //all human players eliminated
  1855. {
  1856. if (adventureInt)
  1857. {
  1858. GH.terminate_cond.setn(true);
  1859. adventureInt->deactivate();
  1860. if (GH.topInt() == adventureInt)
  1861. GH.popInt(adventureInt);
  1862. delete adventureInt;
  1863. adventureInt = nullptr;
  1864. }
  1865. }
  1866. if (cb->getStartInfo()->mode == StartInfo::CAMPAIGN)
  1867. {
  1868. // if you lose the campaign go back to the main menu
  1869. // campaign wins are handled in proposeNextMission
  1870. if (victoryLossCheckResult.loss()) requestReturningToMainMenu();
  1871. }
  1872. else
  1873. {
  1874. if(howManyPeople == 0 && !settings["session"]["spectate"].Bool()) //all human players eliminated
  1875. {
  1876. requestReturningToMainMenu();
  1877. }
  1878. else if (victoryLossCheckResult.victory() && LOCPLINT == this) // end game if current human player has won
  1879. {
  1880. requestReturningToMainMenu();
  1881. }
  1882. }
  1883. if (GH.curInt == this) GH.curInt = nullptr;
  1884. }
  1885. else
  1886. {
  1887. if (victoryLossCheckResult.loss() && cb->getPlayerStatus(playerID) == EPlayerStatus::INGAME) //enemy has lost
  1888. {
  1889. std::string str = victoryLossCheckResult.messageToSelf;
  1890. boost::algorithm::replace_first(str, "%s", CGI->generaltexth->capColors[player.getNum()]);
  1891. showInfoDialog(str, std::vector<CComponent*>(1, new CComponent(CComponent::flag, player.getNum(), 0)));
  1892. }
  1893. }
  1894. }
  1895. void CPlayerInterface::playerBonusChanged( const Bonus &bonus, bool gain )
  1896. {
  1897. EVENT_HANDLER_CALLED_BY_CLIENT;
  1898. }
  1899. void CPlayerInterface::showPuzzleMap()
  1900. {
  1901. EVENT_HANDLER_CALLED_BY_CLIENT;
  1902. waitWhileDialog();
  1903. //TODO: interface should not know the real position of Grail...
  1904. double ratio = 0;
  1905. int3 grailPos = cb->getGrailPos(&ratio);
  1906. GH.pushInt(new CPuzzleWindow(grailPos, ratio));
  1907. }
  1908. void CPlayerInterface::viewWorldMap()
  1909. {
  1910. adventureInt->changeMode(EAdvMapMode::WORLD_VIEW);
  1911. }
  1912. void CPlayerInterface::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  1913. {
  1914. EVENT_HANDLER_CALLED_BY_CLIENT;
  1915. if (spellID == SpellID::FLY || spellID == SpellID::WATER_WALK)
  1916. {
  1917. eraseCurrentPathOf(caster, false);
  1918. }
  1919. const CSpell * spell = CGI->spellh->objects[spellID];
  1920. if (spellID == SpellID::VIEW_EARTH)
  1921. {
  1922. //TODO: implement on server side
  1923. int level = caster->getSpellSchoolLevel(spell);
  1924. adventureInt->worldViewOptions.showAllTerrain = (level>2);
  1925. }
  1926. auto castSoundPath = spell->getCastSound();
  1927. if (!castSoundPath.empty())
  1928. CCS->soundh->playSound(castSoundPath);
  1929. }
  1930. void CPlayerInterface::eraseCurrentPathOf( const CGHeroInstance * ho, bool checkForExistanceOfPath /*= true */ )
  1931. {
  1932. if (checkForExistanceOfPath)
  1933. {
  1934. assert(vstd::contains(paths, ho));
  1935. }
  1936. else if (!vstd::contains(paths, ho))
  1937. {
  1938. return;
  1939. }
  1940. assert(ho == adventureInt->selection);
  1941. paths.erase(ho);
  1942. adventureInt->terrain.currentPath = nullptr;
  1943. adventureInt->updateMoveHero(ho, false);
  1944. }
  1945. void CPlayerInterface::removeLastNodeFromPath(const CGHeroInstance *ho)
  1946. {
  1947. adventureInt->terrain.currentPath->nodes.erase(adventureInt->terrain.currentPath->nodes.end()-1);
  1948. if (adventureInt->terrain.currentPath->nodes.size() < 2) //if it was the last one, remove entire path and path with only one tile is not a real path
  1949. eraseCurrentPathOf(ho);
  1950. }
  1951. CGPath * CPlayerInterface::getAndVerifyPath(const CGHeroInstance * h)
  1952. {
  1953. if (vstd::contains(paths,h)) //hero has assigned path
  1954. {
  1955. CGPath &path = paths[h];
  1956. if (!path.nodes.size())
  1957. {
  1958. logGlobal->warnStream() << "Warning: empty path found...";
  1959. paths.erase(h);
  1960. }
  1961. else
  1962. {
  1963. assert(h->getPosition(false) == path.startPos());
  1964. //update the hero path in case of something has changed on map
  1965. if (LOCPLINT->cb->getPathsInfo(h)->getPath(path, path.endPos()))
  1966. return &path;
  1967. else
  1968. paths.erase(h);
  1969. }
  1970. }
  1971. return nullptr;
  1972. }
  1973. void CPlayerInterface::acceptTurn()
  1974. {
  1975. bool centerView = true;
  1976. if (settings["session"]["autoSkip"].Bool())
  1977. {
  1978. centerView = false;
  1979. while(CInfoWindow *iw = dynamic_cast<CInfoWindow *>(GH.topInt()))
  1980. iw->close();
  1981. }
  1982. waitWhileDialog();
  1983. if (howManyPeople > 1)
  1984. adventureInt->startTurn();
  1985. adventureInt->heroList.update();
  1986. adventureInt->townList.update();
  1987. const CGHeroInstance * heroToSelect = nullptr;
  1988. // find first non-sleeping hero
  1989. for (auto hero : wanderingHeroes)
  1990. {
  1991. if (boost::range::find(sleepingHeroes, hero) == sleepingHeroes.end())
  1992. {
  1993. heroToSelect = hero;
  1994. break;
  1995. }
  1996. }
  1997. //select first hero if available.
  1998. if (heroToSelect != nullptr)
  1999. {
  2000. adventureInt->select(heroToSelect, centerView);
  2001. }
  2002. else if (towns.size())
  2003. adventureInt->select(towns.front(), centerView);
  2004. else
  2005. adventureInt->select(wanderingHeroes.front());
  2006. //show new day animation and sound on infobar
  2007. adventureInt->infoBar.showDate();
  2008. adventureInt->updateNextHero(nullptr);
  2009. adventureInt->showAll(screen);
  2010. if (settings["session"]["autoSkip"].Bool() && !LOCPLINT->shiftPressed())
  2011. {
  2012. if (CInfoWindow *iw = dynamic_cast<CInfoWindow *>(GH.topInt()))
  2013. iw->close();
  2014. adventureInt->fendTurn();
  2015. }
  2016. // warn player if he has no town
  2017. if (cb->howManyTowns() == 0)
  2018. {
  2019. auto playerColor = *cb->getPlayerID();
  2020. std::vector<Component> components;
  2021. components.push_back(Component(Component::FLAG, playerColor.getNum(), 0, 0));
  2022. MetaString text;
  2023. const auto & optDaysWithoutCastle = cb->getPlayer(playerColor)->daysWithoutCastle;
  2024. if(optDaysWithoutCastle)
  2025. {
  2026. auto daysWithoutCastle = optDaysWithoutCastle.get();
  2027. if (daysWithoutCastle < 6)
  2028. {
  2029. 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.
  2030. text.addReplacement(MetaString::COLOR, playerColor.getNum());
  2031. text.addReplacement(7 - daysWithoutCastle);
  2032. }
  2033. else if (daysWithoutCastle == 6)
  2034. {
  2035. text.addTxt(MetaString::ARRAY_TXT,129); //%s, this is your last day to capture a town or you will be banished from this land.
  2036. text.addReplacement(MetaString::COLOR, playerColor.getNum());
  2037. }
  2038. showInfoDialogAndWait(components, text);
  2039. }
  2040. else
  2041. logGlobal->warn("Player has no towns, but daysWithoutCastle is not set");
  2042. }
  2043. }
  2044. void CPlayerInterface::tryDiggging(const CGHeroInstance *h)
  2045. {
  2046. std::string hlp;
  2047. CGI->mh->getTerrainDescr(h->getPosition(false), hlp, false);
  2048. auto isDiggingPossible = h->diggingStatus();
  2049. if (hlp.length())
  2050. isDiggingPossible = EDiggingStatus::TILE_OCCUPIED; //TODO integrate with canDig
  2051. int msgToShow = -1;
  2052. switch(isDiggingPossible)
  2053. {
  2054. case EDiggingStatus::CAN_DIG:
  2055. break;
  2056. case EDiggingStatus::LACK_OF_MOVEMENT:
  2057. msgToShow = 56; //"Digging for artifacts requires a whole day, try again tomorrow."
  2058. break;
  2059. case EDiggingStatus::TILE_OCCUPIED:
  2060. msgToShow = 97; //Try searching on clear ground.
  2061. break;
  2062. case EDiggingStatus::WRONG_TERRAIN:
  2063. msgToShow = 60; ////Try looking on land!
  2064. break;
  2065. default:
  2066. assert(0);
  2067. }
  2068. if (msgToShow < 0)
  2069. cb->dig(h);
  2070. else
  2071. showInfoDialog(CGI->generaltexth->allTexts[msgToShow]);
  2072. }
  2073. void CPlayerInterface::updateInfo(const CGObjectInstance * specific)
  2074. {
  2075. adventureInt->infoBar.showSelection();
  2076. }
  2077. void CPlayerInterface::battleNewRoundFirst( int round )
  2078. {
  2079. EVENT_HANDLER_CALLED_BY_CLIENT;
  2080. BATTLE_EVENT_POSSIBLE_RETURN;
  2081. battleInt->newRoundFirst(round);
  2082. }
  2083. void CPlayerInterface::stopMovement()
  2084. {
  2085. if (stillMoveHero.get() == DURING_MOVE)//if we are in the middle of hero movement
  2086. stillMoveHero.setn(STOP_MOVE); //after showing dialog movement will be stopped
  2087. }
  2088. void CPlayerInterface::showMarketWindow(const IMarket *market, const CGHeroInstance *visitor)
  2089. {
  2090. EVENT_HANDLER_CALLED_BY_CLIENT;
  2091. if (market->o->ID == Obj::ALTAR_OF_SACRIFICE)
  2092. {
  2093. //EEMarketMode mode = market->availableModes().front();
  2094. if (market->allowsTrade(EMarketMode::ARTIFACT_EXP) && visitor->getAlignment() != EAlignment::EVIL)
  2095. GH.pushInt(new CAltarWindow(market, visitor, EMarketMode::ARTIFACT_EXP));
  2096. else if (market->allowsTrade(EMarketMode::CREATURE_EXP) && visitor->getAlignment() != EAlignment::GOOD)
  2097. GH.pushInt(new CAltarWindow(market, visitor, EMarketMode::CREATURE_EXP));
  2098. }
  2099. else
  2100. GH.pushInt(new CMarketplaceWindow(market, visitor, market->availableModes().front()));
  2101. }
  2102. void CPlayerInterface::showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor)
  2103. {
  2104. EVENT_HANDLER_CALLED_BY_CLIENT;
  2105. auto cuw = new CUniversityWindow(visitor, market);
  2106. GH.pushInt(cuw);
  2107. }
  2108. void CPlayerInterface::showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor)
  2109. {
  2110. EVENT_HANDLER_CALLED_BY_CLIENT;
  2111. auto chfw = new CHillFortWindow(visitor, object);
  2112. GH.pushInt(chfw);
  2113. }
  2114. void CPlayerInterface::availableArtifactsChanged(const CGBlackMarket *bm /*= nullptr*/)
  2115. {
  2116. EVENT_HANDLER_CALLED_BY_CLIENT;
  2117. if (CMarketplaceWindow *cmw = dynamic_cast<CMarketplaceWindow*>(GH.topInt()))
  2118. cmw->artifactsChanged(false);
  2119. }
  2120. void CPlayerInterface::showTavernWindow(const CGObjectInstance *townOrTavern)
  2121. {
  2122. EVENT_HANDLER_CALLED_BY_CLIENT;
  2123. auto tv = new CTavernWindow(townOrTavern);
  2124. GH.pushInt(tv);
  2125. }
  2126. void CPlayerInterface::showThievesGuildWindow (const CGObjectInstance * obj)
  2127. {
  2128. EVENT_HANDLER_CALLED_BY_CLIENT;
  2129. auto tgw = new CThievesGuildWindow(obj);
  2130. GH.pushInt(tgw);
  2131. }
  2132. void CPlayerInterface::showQuestLog()
  2133. {
  2134. EVENT_HANDLER_CALLED_BY_CLIENT;
  2135. CQuestLog * ql = new CQuestLog (LOCPLINT->cb->getMyQuests());
  2136. GH.pushInt (ql);
  2137. }
  2138. void CPlayerInterface::showShipyardDialogOrProblemPopup(const IShipyard *obj)
  2139. {
  2140. if (obj->shipyardStatus() != IBoatGenerator::GOOD)
  2141. {
  2142. MetaString txt;
  2143. obj->getProblemText(txt);
  2144. showInfoDialog(txt.toString());
  2145. }
  2146. else
  2147. showShipyardDialog(obj);
  2148. }
  2149. void CPlayerInterface::requestReturningToMainMenu()
  2150. {
  2151. sendCustomEvent(RETURN_TO_MAIN_MENU);
  2152. cb->unregisterAllInterfaces();
  2153. }
  2154. void CPlayerInterface::sendCustomEvent( int code )
  2155. {
  2156. CGuiHandler::pushSDLEvent(SDL_USEREVENT, code);
  2157. }
  2158. void CPlayerInterface::stackChagedCount(const StackLocation &location, const TQuantity &change, bool isAbsolute)
  2159. {
  2160. EVENT_HANDLER_CALLED_BY_CLIENT;
  2161. garrisonChanged(location.army);
  2162. }
  2163. void CPlayerInterface::stackChangedType(const StackLocation &location, const CCreature &newType)
  2164. {
  2165. EVENT_HANDLER_CALLED_BY_CLIENT;
  2166. garrisonChanged(location.army);
  2167. }
  2168. void CPlayerInterface::stacksErased(const StackLocation &location)
  2169. {
  2170. EVENT_HANDLER_CALLED_BY_CLIENT;
  2171. garrisonChanged(location.army);
  2172. }
  2173. void CPlayerInterface::stacksSwapped(const StackLocation &loc1, const StackLocation &loc2)
  2174. {
  2175. EVENT_HANDLER_CALLED_BY_CLIENT;
  2176. std::vector<const CGObjectInstance *> objects;
  2177. objects.push_back(loc1.army);
  2178. if (loc2.army != loc1.army)
  2179. objects.push_back(loc2.army);
  2180. garrisonsChanged(objects);
  2181. }
  2182. void CPlayerInterface::newStackInserted(const StackLocation &location, const CStackInstance &stack)
  2183. {
  2184. EVENT_HANDLER_CALLED_BY_CLIENT;
  2185. garrisonChanged(location.army);
  2186. }
  2187. void CPlayerInterface::stacksRebalanced(const StackLocation &src, const StackLocation &dst, TQuantity count)
  2188. {
  2189. EVENT_HANDLER_CALLED_BY_CLIENT;
  2190. std::vector<const CGObjectInstance *> objects;
  2191. objects.push_back(src.army);
  2192. if (src.army != dst.army)
  2193. objects.push_back(dst.army);
  2194. garrisonsChanged(objects);
  2195. }
  2196. void CPlayerInterface::askToAssembleArtifact(const ArtifactLocation &al)
  2197. {
  2198. auto hero = boost::apply_visitor(HeroObjectRetriever(), al.artHolder);
  2199. if(hero)
  2200. {
  2201. auto art = hero->getArt(al.slot);
  2202. if(art == nullptr)
  2203. {
  2204. logGlobal->error("artifact location %d points to nothing",
  2205. al.slot.num);
  2206. return;
  2207. }
  2208. CHeroArtPlace::askToAssemble(art, al.slot, hero);
  2209. }
  2210. }
  2211. void CPlayerInterface::artifactPut(const ArtifactLocation &al)
  2212. {
  2213. EVENT_HANDLER_CALLED_BY_CLIENT;
  2214. adventureInt->infoBar.showSelection();
  2215. askToAssembleArtifact(al);
  2216. }
  2217. void CPlayerInterface::artifactRemoved(const ArtifactLocation &al)
  2218. {
  2219. EVENT_HANDLER_CALLED_BY_CLIENT;
  2220. adventureInt->infoBar.showSelection();
  2221. for (IShowActivatable *isa : GH.listInt)
  2222. {
  2223. auto artWin = dynamic_cast<CArtifactHolder*>(isa);
  2224. if (artWin)
  2225. artWin->artifactRemoved(al);
  2226. }
  2227. }
  2228. void CPlayerInterface::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  2229. {
  2230. EVENT_HANDLER_CALLED_BY_CLIENT;
  2231. adventureInt->infoBar.showSelection();
  2232. for (IShowActivatable *isa : GH.listInt)
  2233. {
  2234. auto artWin = dynamic_cast<CArtifactHolder*>(isa);
  2235. if (artWin)
  2236. artWin->artifactMoved(src, dst);
  2237. }
  2238. askToAssembleArtifact(dst);
  2239. }
  2240. void CPlayerInterface::artifactAssembled(const ArtifactLocation &al)
  2241. {
  2242. EVENT_HANDLER_CALLED_BY_CLIENT;
  2243. adventureInt->infoBar.showSelection();
  2244. for (IShowActivatable *isa : GH.listInt)
  2245. {
  2246. auto artWin = dynamic_cast<CArtifactHolder*>(isa);
  2247. if (artWin)
  2248. artWin->artifactAssembled(al);
  2249. }
  2250. }
  2251. void CPlayerInterface::artifactDisassembled(const ArtifactLocation &al)
  2252. {
  2253. EVENT_HANDLER_CALLED_BY_CLIENT;
  2254. adventureInt->infoBar.showSelection();
  2255. for (IShowActivatable *isa : GH.listInt)
  2256. {
  2257. auto artWin = dynamic_cast<CArtifactHolder*>(isa);
  2258. if (artWin)
  2259. artWin->artifactDisassembled(al);
  2260. }
  2261. }
  2262. void CPlayerInterface::playerStartsTurn(PlayerColor player)
  2263. {
  2264. EVENT_HANDLER_CALLED_BY_CLIENT;
  2265. if (!vstd::contains (GH.listInt, adventureInt))
  2266. {
  2267. GH.popInts (GH.listInt.size()); //after map load - remove everything else
  2268. GH.pushInt (adventureInt);
  2269. }
  2270. else
  2271. {
  2272. adventureInt->infoBar.showSelection();
  2273. while (GH.listInt.front() != adventureInt && !dynamic_cast<CInfoWindow*>(GH.listInt.front())) //don't remove dialogs that expect query answer
  2274. GH.popInts(1);
  2275. }
  2276. if (howManyPeople == 1)
  2277. {
  2278. GH.curInt = this;
  2279. adventureInt->startTurn();
  2280. }
  2281. if (player != playerID && this == LOCPLINT)
  2282. {
  2283. waitWhileDialog();
  2284. adventureInt->aiTurnStarted();
  2285. }
  2286. }
  2287. void CPlayerInterface::waitForAllDialogs(bool unlockPim /*= true*/)
  2288. {
  2289. while(!dialogs.empty())
  2290. {
  2291. auto unlock = vstd::makeUnlockGuardIf(*pim, unlockPim);
  2292. SDL_Delay(5);
  2293. }
  2294. waitWhileDialog(unlockPim);
  2295. }
  2296. void CPlayerInterface::proposeLoadingGame()
  2297. {
  2298. showYesNoDialog(CGI->generaltexth->allTexts[68], [this] { sendCustomEvent(RETURN_TO_MENU_LOAD); }, 0, false);
  2299. }
  2300. CPlayerInterface::SpellbookLastSetting::SpellbookLastSetting()
  2301. {
  2302. spellbookLastPageBattle = spellbokLastPageAdvmap = 0;
  2303. spellbookLastTabBattle = spellbookLastTabAdvmap = 4;
  2304. }
  2305. bool CPlayerInterface::capturedAllEvents()
  2306. {
  2307. if (duringMovement)
  2308. {
  2309. //just inform that we are capturing events. they will be processed by heroMoved() in client thread.
  2310. return true;
  2311. }
  2312. if (ignoreEvents)
  2313. {
  2314. boost::unique_lock<boost::mutex> un(eventsM);
  2315. while(!events.empty())
  2316. {
  2317. events.pop();
  2318. }
  2319. return true;
  2320. }
  2321. return false;
  2322. }
  2323. void CPlayerInterface::setMovementStatus(bool value)
  2324. {
  2325. duringMovement = value;
  2326. if (value)
  2327. {
  2328. CCS->curh->hide();
  2329. }
  2330. else
  2331. {
  2332. CCS->curh->show();
  2333. }
  2334. }
  2335. void CPlayerInterface::doMoveHero(const CGHeroInstance * h, CGPath path)
  2336. {
  2337. int i = 1;
  2338. auto getObj = [&](int3 coord, bool ignoreHero)
  2339. {
  2340. return cb->getTile(CGHeroInstance::convertPosition(coord,false))->topVisitableObj(ignoreHero);
  2341. };
  2342. auto isTeleportAction = [&](CGPathNode::ENodeAction action) -> bool
  2343. {
  2344. if (action != CGPathNode::TELEPORT_NORMAL &&
  2345. action != CGPathNode::TELEPORT_BLOCKING_VISIT &&
  2346. action != CGPathNode::TELEPORT_BATTLE)
  2347. {
  2348. return false;
  2349. }
  2350. return true;
  2351. };
  2352. auto getDestTeleportObj = [&](const CGObjectInstance * currentObject, const CGObjectInstance * nextObjectTop, const CGObjectInstance * nextObject) -> const CGObjectInstance *
  2353. {
  2354. if (CGTeleport::isConnected(currentObject, nextObjectTop))
  2355. return nextObjectTop;
  2356. if (nextObjectTop && nextObjectTop->ID == Obj::HERO &&
  2357. CGTeleport::isConnected(currentObject, nextObject))
  2358. {
  2359. return nextObject;
  2360. }
  2361. return nullptr;
  2362. };
  2363. boost::unique_lock<boost::mutex> un(stillMoveHero.mx);
  2364. stillMoveHero.data = CONTINUE_MOVE;
  2365. auto doMovement = [&](int3 dst, bool transit)
  2366. {
  2367. stillMoveHero.data = WAITING_MOVE;
  2368. cb->moveHero(h, dst, transit);
  2369. while(stillMoveHero.data != STOP_MOVE && stillMoveHero.data != CONTINUE_MOVE)
  2370. stillMoveHero.cond.wait(un);
  2371. };
  2372. {
  2373. path.convert(0);
  2374. ETerrainType currentTerrain = ETerrainType::BORDER; // not init yet
  2375. ETerrainType newTerrain;
  2376. int sh = -1;
  2377. auto canStop = [&](CGPathNode * node) -> bool
  2378. {
  2379. if (node->layer == EPathfindingLayer::LAND || node->layer == EPathfindingLayer::SAIL)
  2380. return true;
  2381. if (node->accessible == CGPathNode::ACCESSIBLE)
  2382. return true;
  2383. return false;
  2384. };
  2385. for (i=path.nodes.size()-1; i>0 && (stillMoveHero.data == CONTINUE_MOVE || !canStop(&path.nodes[i])); i--)
  2386. {
  2387. int3 currentCoord = path.nodes[i].coord;
  2388. int3 nextCoord = path.nodes[i-1].coord;
  2389. auto currentObject = getObj(currentCoord, currentCoord == h->pos);
  2390. auto nextObjectTop = getObj(nextCoord, false);
  2391. auto nextObject = getObj(nextCoord, true);
  2392. auto destTeleportObj = getDestTeleportObj(currentObject, nextObjectTop, nextObject);
  2393. if (isTeleportAction(path.nodes[i-1].action) && destTeleportObj != nullptr)
  2394. {
  2395. CCS->soundh->stopSound(sh);
  2396. destinationTeleport = destTeleportObj->id;
  2397. destinationTeleportPos = nextCoord;
  2398. doMovement(h->pos, false);
  2399. if (path.nodes[i-1].action == CGPathNode::TELEPORT_BLOCKING_VISIT)
  2400. {
  2401. destinationTeleport = ObjectInstanceID();
  2402. destinationTeleportPos = int3(-1);
  2403. }
  2404. sh = CCS->soundh->playSound(CCS->soundh->horseSounds[currentTerrain], -1);
  2405. continue;
  2406. }
  2407. if (path.nodes[i-1].turns)
  2408. { //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  2409. stillMoveHero.data = STOP_MOVE;
  2410. break;
  2411. }
  2412. // Start a new sound for the hero movement or let the existing one carry on.
  2413. #if 0
  2414. // TODO
  2415. if (hero is flying && sh == -1)
  2416. sh = CCS->soundh->playSound(soundBase::horseFlying, -1);
  2417. #endif
  2418. {
  2419. newTerrain = cb->getTile(CGHeroInstance::convertPosition(currentCoord, false))->terType;
  2420. if (newTerrain != currentTerrain)
  2421. {
  2422. CCS->soundh->stopSound(sh);
  2423. sh = CCS->soundh->playSound(CCS->soundh->horseSounds[newTerrain], -1);
  2424. currentTerrain = newTerrain;
  2425. }
  2426. }
  2427. 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
  2428. int3 endpos(nextCoord.x, nextCoord.y, h->pos.z);
  2429. logGlobal->traceStream() << "Requesting hero movement to " << endpos;
  2430. bool useTransit = false;
  2431. if ((i-2 >= 0) // Check there is node after next one; otherwise transit is pointless
  2432. && (CGTeleport::isConnected(nextObjectTop, getObj(path.nodes[i-2].coord, false))
  2433. || CGTeleport::isTeleport(nextObjectTop)))
  2434. { // Hero should be able to go through object if it's allow transit
  2435. useTransit = true;
  2436. }
  2437. else if (path.nodes[i-1].layer == EPathfindingLayer::AIR)
  2438. useTransit = true;
  2439. doMovement(endpos, useTransit);
  2440. logGlobal->traceStream() << "Resuming " << __FUNCTION__;
  2441. bool guarded = cb->isInTheMap(cb->getGuardingCreaturePosition(endpos - int3(1, 0, 0)));
  2442. if ((!useTransit && guarded) || showingDialog->get() == true) // Abort movement if a guard was fought or there is a dialog to display (Mantis #1136)
  2443. break;
  2444. }
  2445. CCS->soundh->stopSound(sh);
  2446. }
  2447. //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
  2448. if (!showingDialog->get())
  2449. GH.fakeMouseMove();
  2450. //todo: this should be in main thread
  2451. if (adventureInt)
  2452. {
  2453. // (i == 0) means hero went through all the path
  2454. adventureInt->updateMoveHero(h, (i != 0));
  2455. adventureInt->updateNextHero(h);
  2456. }
  2457. setMovementStatus(false);
  2458. }
  2459. void CPlayerInterface::showWorldViewEx(const std::vector<ObjectPosInfo>& objectPositions)
  2460. {
  2461. EVENT_HANDLER_CALLED_BY_CLIENT;
  2462. //TODO: showWorldViewEx
  2463. std::copy(objectPositions.begin(), objectPositions.end(), std::back_inserter(adventureInt->worldViewOptions.iconPositions));
  2464. viewWorldMap();
  2465. }