CPlayerInterface.cpp 75 KB

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