CPlayerInterface.cpp 93 KB

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