CPlayerInterface.cpp 96 KB

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