2
0

CPlayerInterface.cpp 97 KB

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