CPlayerInterface.cpp 97 KB

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