CPlayerInterface.cpp 94 KB

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