CPlayerInterface.cpp 95 KB

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