CBattleInterface.cpp 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163
  1. /*
  2. * CBattleInterface.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 "CBattleInterface.h"
  12. #include "CBattleAnimations.h"
  13. #include "CBattleInterfaceClasses.h"
  14. #include "CCreatureAnimation.h"
  15. #include "CBattleProjectileController.h"
  16. #include "CBattleObstacleController.h"
  17. #include "CBattleSiegeController.h"
  18. #include "../CBitmapHandler.h"
  19. #include "../CGameInfo.h"
  20. #include "../CMessage.h"
  21. #include "../CMT.h"
  22. #include "../CMusicHandler.h"
  23. #include "../CPlayerInterface.h"
  24. #include "../CVideoHandler.h"
  25. #include "../Graphics.h"
  26. #include "../gui/CAnimation.h"
  27. #include "../gui/CCursorHandler.h"
  28. #include "../gui/CGuiHandler.h"
  29. #include "../gui/SDL_Extensions.h"
  30. #include "../windows/CAdvmapInterface.h"
  31. #include "../windows/CCreatureWindow.h"
  32. #include "../windows/CSpellWindow.h"
  33. #include "../../CCallback.h"
  34. #include "../../lib/CStack.h"
  35. #include "../../lib/CConfigHandler.h"
  36. #include "../../lib/CGeneralTextHandler.h"
  37. #include "../../lib/CHeroHandler.h"
  38. #include "../../lib/CondSh.h"
  39. #include "../../lib/CRandomGenerator.h"
  40. #include "../../lib/spells/CSpellHandler.h"
  41. #include "../../lib/spells/ISpellMechanics.h"
  42. #include "../../lib/spells/Problem.h"
  43. #include "../../lib/CTownHandler.h"
  44. #include "../../lib/BattleFieldHandler.h"
  45. #include "../../lib/ObstacleHandler.h"
  46. #include "../../lib/CGameState.h"
  47. #include "../../lib/mapping/CMap.h"
  48. #include "../../lib/NetPacks.h"
  49. #include "../../lib/UnlockGuard.h"
  50. CondSh<bool> CBattleInterface::animsAreDisplayed(false);
  51. CondSh<BattleAction *> CBattleInterface::givenCommand(nullptr);
  52. static void onAnimationFinished(const CStack *stack, std::weak_ptr<CCreatureAnimation> anim)
  53. {
  54. std::shared_ptr<CCreatureAnimation> animation = anim.lock();
  55. if(!animation)
  56. return;
  57. if (animation->isIdle())
  58. {
  59. const CCreature *creature = stack->getCreature();
  60. if (animation->framesInGroup(CCreatureAnim::MOUSEON) > 0)
  61. {
  62. if (CRandomGenerator::getDefault().nextDouble(99.0) < creature->animation.timeBetweenFidgets *10)
  63. animation->playOnce(CCreatureAnim::MOUSEON);
  64. else
  65. animation->setType(CCreatureAnim::HOLDING);
  66. }
  67. else
  68. {
  69. animation->setType(CCreatureAnim::HOLDING);
  70. }
  71. }
  72. // always reset callback
  73. animation->onAnimationReset += std::bind(&onAnimationFinished, stack, anim);
  74. }
  75. static void transformPalette(SDL_Surface *surf, double rCor, double gCor, double bCor)
  76. {
  77. SDL_Color *colorsToChange = surf->format->palette->colors;
  78. for (int g=0; g<surf->format->palette->ncolors; ++g)
  79. {
  80. SDL_Color *color = &colorsToChange[g];
  81. if (color->b != 132 &&
  82. color->g != 231 &&
  83. color->r != 255) //it's not yellow border
  84. {
  85. color->r = static_cast<Uint8>(color->r * rCor);
  86. color->g = static_cast<Uint8>(color->g * gCor);
  87. color->b = static_cast<Uint8>(color->b * bCor);
  88. }
  89. }
  90. }
  91. void CBattleInterface::addNewAnim(CBattleAnimation *anim)
  92. {
  93. pendingAnims.push_back( std::make_pair(anim, false) );
  94. animsAreDisplayed.setn(true);
  95. }
  96. CBattleInterface::CBattleInterface(const CCreatureSet *army1, const CCreatureSet *army2,
  97. const CGHeroInstance *hero1, const CGHeroInstance *hero2,
  98. const SDL_Rect & myRect,
  99. std::shared_ptr<CPlayerInterface> att, std::shared_ptr<CPlayerInterface> defen, std::shared_ptr<CPlayerInterface> spectatorInt)
  100. : background(nullptr), attackingHeroInstance(hero1), defendingHeroInstance(hero2), animCount(0),
  101. activeStack(nullptr), mouseHoveredStack(nullptr), stackToActivate(nullptr), selectedStack(nullptr), previouslyHoveredHex(-1),
  102. currentlyHoveredHex(-1), attackingHex(-1), stackCanCastSpell(false), creatureCasting(false), spellDestSelectMode(false), spellToCast(nullptr), sp(nullptr),
  103. creatureSpellToCast(-1),
  104. attackerInt(att), defenderInt(defen), curInt(att), animIDhelper(0),
  105. myTurn(false), moveStarted(false), moveSoundHander(-1), bresult(nullptr), battleActionsStarted(false)
  106. {
  107. OBJ_CONSTRUCTION;
  108. projectilesController.reset(new CBattleProjectileController(this));
  109. if(spectatorInt)
  110. {
  111. curInt = spectatorInt;
  112. }
  113. else if(!curInt)
  114. {
  115. //May happen when we are defending during network MP game -> attacker interface is just not present
  116. curInt = defenderInt;
  117. }
  118. animsAreDisplayed.setn(false);
  119. pos = myRect;
  120. strongInterest = true;
  121. givenCommand.setn(nullptr);
  122. //hot-seat -> check tactics for both players (defender may be local human)
  123. if(attackerInt && attackerInt->cb->battleGetTacticDist())
  124. tacticianInterface = attackerInt;
  125. else if(defenderInt && defenderInt->cb->battleGetTacticDist())
  126. tacticianInterface = defenderInt;
  127. //if we found interface of player with tactics, then enter tactics mode
  128. tacticsMode = static_cast<bool>(tacticianInterface);
  129. //create stack queue
  130. bool embedQueue;
  131. std::string queueSize = settings["battle"]["queueSize"].String();
  132. if(queueSize == "auto")
  133. embedQueue = screen->h < 700;
  134. else
  135. embedQueue = screen->h < 700 || queueSize == "small";
  136. queue = std::make_shared<CStackQueue>(embedQueue, this);
  137. if(!embedQueue)
  138. {
  139. if (settings["battle"]["showQueue"].Bool())
  140. pos.y += queue->pos.h / 2; //center whole window
  141. queue->moveTo(Point(pos.x, pos.y - queue->pos.h));
  142. }
  143. queue->update();
  144. //preparing siege info
  145. const CGTownInstance *town = curInt->cb->battleGetDefendedTown();
  146. if(town && town->hasFort())
  147. siegeController.reset(new CBattleSiegeController(this, town));
  148. CPlayerInterface::battleInt = this;
  149. //initializing armies
  150. this->army1 = army1;
  151. this->army2 = army2;
  152. std::vector<const CStack*> stacks = curInt->cb->battleGetAllStacks(true);
  153. for(const CStack * s : stacks)
  154. {
  155. unitAdded(s);
  156. }
  157. //preparing menu background and terrain
  158. if(!siegeController)
  159. {
  160. auto bfieldType = curInt->cb->battleGetBattlefieldType();
  161. if(bfieldType == BattleField::NONE)
  162. {
  163. logGlobal->error("Invalid battlefield returned for current battle");
  164. }
  165. else
  166. {
  167. background = BitmapHandler::loadBitmap(bfieldType.getInfo()->graphics, false);
  168. }
  169. }
  170. //preparing graphics for displaying amounts of creatures
  171. amountNormal = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
  172. CSDL_Ext::alphaTransform(amountNormal);
  173. transformPalette(amountNormal, 0.59, 0.19, 0.93);
  174. amountPositive = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
  175. CSDL_Ext::alphaTransform(amountPositive);
  176. transformPalette(amountPositive, 0.18, 1.00, 0.18);
  177. amountNegative = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
  178. CSDL_Ext::alphaTransform(amountNegative);
  179. transformPalette(amountNegative, 1.00, 0.18, 0.18);
  180. amountEffNeutral = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
  181. CSDL_Ext::alphaTransform(amountEffNeutral);
  182. transformPalette(amountEffNeutral, 1.00, 1.00, 0.18);
  183. //preparing buttons and console
  184. bOptions = std::make_shared<CButton>(Point( 3, 561), "icm003.def", CGI->generaltexth->zelp[381], std::bind(&CBattleInterface::bOptionsf,this), SDLK_o);
  185. bSurrender = std::make_shared<CButton>(Point( 54, 561), "icm001.def", CGI->generaltexth->zelp[379], std::bind(&CBattleInterface::bSurrenderf,this), SDLK_s);
  186. bFlee = std::make_shared<CButton>(Point(105, 561), "icm002.def", CGI->generaltexth->zelp[380], std::bind(&CBattleInterface::bFleef,this), SDLK_r);
  187. bAutofight = std::make_shared<CButton>(Point(157, 561), "icm004.def", CGI->generaltexth->zelp[382], std::bind(&CBattleInterface::bAutofightf,this), SDLK_a);
  188. bSpell = std::make_shared<CButton>(Point(645, 561), "icm005.def", CGI->generaltexth->zelp[385], std::bind(&CBattleInterface::bSpellf,this), SDLK_c);
  189. bWait = std::make_shared<CButton>(Point(696, 561), "icm006.def", CGI->generaltexth->zelp[386], std::bind(&CBattleInterface::bWaitf,this), SDLK_w);
  190. bDefence = std::make_shared<CButton>(Point(747, 561), "icm007.def", CGI->generaltexth->zelp[387], std::bind(&CBattleInterface::bDefencef,this), SDLK_d);
  191. bDefence->assignedKeys.insert(SDLK_SPACE);
  192. bConsoleUp = std::make_shared<CButton>(Point(624, 561), "ComSlide.def", std::make_pair("", ""), std::bind(&CBattleInterface::bConsoleUpf,this), SDLK_UP);
  193. bConsoleDown = std::make_shared<CButton>(Point(624, 580), "ComSlide.def", std::make_pair("", ""), std::bind(&CBattleInterface::bConsoleDownf,this), SDLK_DOWN);
  194. bConsoleUp->setImageOrder(0, 1, 0, 0);
  195. bConsoleDown->setImageOrder(2, 3, 2, 2);
  196. console = std::make_shared<CBattleConsole>();
  197. console->pos.x += 211;
  198. console->pos.y += 560;
  199. console->pos.w = 406;
  200. console->pos.h = 38;
  201. if(tacticsMode)
  202. {
  203. btactNext = std::make_shared<CButton>(Point(213, 560), "icm011.def", std::make_pair("", ""), [&](){ bTacticNextStack(nullptr);}, SDLK_SPACE);
  204. btactEnd = std::make_shared<CButton>(Point(419, 560), "icm012.def", std::make_pair("", ""), [&](){ bEndTacticPhase();}, SDLK_RETURN);
  205. menu = BitmapHandler::loadBitmap("COPLACBR.BMP");
  206. }
  207. else
  208. {
  209. menu = BitmapHandler::loadBitmap("CBAR.BMP");
  210. }
  211. graphics->blueToPlayersAdv(menu, curInt->playerID);
  212. //loading hero animations
  213. if(hero1) // attacking hero
  214. {
  215. std::string battleImage;
  216. if(!hero1->type->battleImage.empty())
  217. {
  218. battleImage = hero1->type->battleImage;
  219. }
  220. else
  221. {
  222. if(hero1->sex)
  223. battleImage = hero1->type->heroClass->imageBattleFemale;
  224. else
  225. battleImage = hero1->type->heroClass->imageBattleMale;
  226. }
  227. attackingHero = std::make_shared<CBattleHero>(battleImage, false, hero1->tempOwner, hero1->tempOwner == curInt->playerID ? hero1 : nullptr, this);
  228. auto img = attackingHero->animation->getImage(0, 0, true);
  229. if(img)
  230. attackingHero->pos = genRect(img->height(), img->width(), pos.x - 43, pos.y - 19);
  231. }
  232. if(hero2) // defending hero
  233. {
  234. std::string battleImage;
  235. if(!hero2->type->battleImage.empty())
  236. {
  237. battleImage = hero2->type->battleImage;
  238. }
  239. else
  240. {
  241. if(hero2->sex)
  242. battleImage = hero2->type->heroClass->imageBattleFemale;
  243. else
  244. battleImage = hero2->type->heroClass->imageBattleMale;
  245. }
  246. defendingHero = std::make_shared<CBattleHero>(battleImage, true, hero2->tempOwner, hero2->tempOwner == curInt->playerID ? hero2 : nullptr, this);
  247. auto img = defendingHero->animation->getImage(0, 0, true);
  248. if(img)
  249. defendingHero->pos = genRect(img->height(), img->width(), pos.x + 693, pos.y - 19);
  250. }
  251. //preparing cells and hexes
  252. cellBorder = BitmapHandler::loadBitmap("CCELLGRD.BMP");
  253. CSDL_Ext::alphaTransform(cellBorder);
  254. cellShade = BitmapHandler::loadBitmap("CCELLSHD.BMP");
  255. CSDL_Ext::alphaTransform(cellShade);
  256. for (int h = 0; h < GameConstants::BFIELD_SIZE; ++h)
  257. {
  258. auto hex = std::make_shared<CClickableHex>();
  259. hex->myNumber = h;
  260. hex->pos = hexPosition(h);
  261. hex->accessible = true;
  262. hex->myInterface = this;
  263. bfield.push_back(hex);
  264. }
  265. //locking occupied positions on batlefield
  266. for(const CStack * s : stacks) //stacks gained at top of this function
  267. if(s->initialPosition >= 0) //turrets have position < 0
  268. bfield[s->getPosition()]->accessible = false;
  269. //preparing graphic with cell borders
  270. cellBorders = CSDL_Ext::newSurface(background->w, background->h, cellBorder);
  271. //copying palette
  272. for (int g=0; g<cellBorder->format->palette->ncolors; ++g) //we assume that cellBorders->format->palette->ncolors == 256
  273. {
  274. cellBorders->format->palette->colors[g] = cellBorder->format->palette->colors[g];
  275. }
  276. //palette copied
  277. for (int i=0; i<GameConstants::BFIELD_HEIGHT; ++i) //rows
  278. {
  279. for (int j=0; j<GameConstants::BFIELD_WIDTH-2; ++j) //columns
  280. {
  281. int x = 58 + (i%2==0 ? 22 : 0) + 44*j;
  282. int y = 86 + 42 *i;
  283. for (int cellX = 0; cellX < cellBorder->w; ++cellX)
  284. {
  285. for (int cellY = 0; cellY < cellBorder->h; ++cellY)
  286. {
  287. if (y+cellY < cellBorders->h && x+cellX < cellBorders->w)
  288. * ((Uint8*)cellBorders->pixels + (y+cellY) *cellBorders->pitch + (x+cellX)) |= *((Uint8*)cellBorder->pixels + cellY *cellBorder->pitch + cellX);
  289. }
  290. }
  291. }
  292. }
  293. backgroundWithHexes = CSDL_Ext::newSurface(background->w, background->h, screen);
  294. obstacleController.reset(new CBattleObstacleController(this));
  295. for(auto hex : bfield)
  296. addChild(hex.get());
  297. if(tacticsMode)
  298. bTacticNextStack();
  299. CCS->musich->stopMusic();
  300. battleIntroSoundChannel = CCS->soundh->playSoundFromSet(CCS->soundh->battleIntroSounds);
  301. auto onIntroPlayed = [&]()
  302. {
  303. if(LOCPLINT->battleInt)
  304. {
  305. CCS->musich->playMusicFromSet("battle", true, true);
  306. battleActionsStarted = true;
  307. blockUI(settings["session"]["spectate"].Bool());
  308. battleIntroSoundChannel = -1;
  309. }
  310. };
  311. CCS->soundh->setCallback(battleIntroSoundChannel, onIntroPlayed);
  312. currentAction = PossiblePlayerBattleAction::INVALID;
  313. selectedAction = PossiblePlayerBattleAction::INVALID;
  314. addUsedEvents(RCLICK | MOVE | KEYBOARD);
  315. blockUI(true);
  316. }
  317. CBattleInterface::~CBattleInterface()
  318. {
  319. CPlayerInterface::battleInt = nullptr;
  320. givenCommand.cond.notify_all(); //that two lines should make any activeStack waiting thread to finish
  321. if (active) //dirty fix for #485
  322. {
  323. deactivate();
  324. }
  325. SDL_FreeSurface(background);
  326. SDL_FreeSurface(menu);
  327. SDL_FreeSurface(amountNormal);
  328. SDL_FreeSurface(amountNegative);
  329. SDL_FreeSurface(amountPositive);
  330. SDL_FreeSurface(amountEffNeutral);
  331. SDL_FreeSurface(cellBorders);
  332. SDL_FreeSurface(backgroundWithHexes);
  333. SDL_FreeSurface(cellBorder);
  334. SDL_FreeSurface(cellShade);
  335. //TODO: play AI tracks if battle was during AI turn
  336. //if (!curInt->makingTurn)
  337. //CCS->musich->playMusicFromSet(CCS->musich->aiMusics, -1);
  338. if (adventureInt && adventureInt->selection)
  339. {
  340. const auto & terrain = *(LOCPLINT->cb->getTile(adventureInt->selection->visitablePos())->terType);
  341. CCS->musich->playMusicFromSet("terrain", terrain.name, true, false);
  342. }
  343. animsAreDisplayed.setn(false);
  344. }
  345. void CBattleInterface::setPrintCellBorders(bool set)
  346. {
  347. Settings cellBorders = settings.write["battle"]["cellBorders"];
  348. cellBorders->Bool() = set;
  349. redrawBackgroundWithHexes(activeStack);
  350. GH.totalRedraw();
  351. }
  352. void CBattleInterface::setPrintStackRange(bool set)
  353. {
  354. Settings stackRange = settings.write["battle"]["stackRange"];
  355. stackRange->Bool() = set;
  356. redrawBackgroundWithHexes(activeStack);
  357. GH.totalRedraw();
  358. }
  359. void CBattleInterface::setPrintMouseShadow(bool set)
  360. {
  361. Settings shadow = settings.write["battle"]["mouseShadow"];
  362. shadow->Bool() = set;
  363. }
  364. void CBattleInterface::activate()
  365. {
  366. if (curInt->isAutoFightOn)
  367. {
  368. bAutofight->activate();
  369. return;
  370. }
  371. CIntObject::activate();
  372. bOptions->activate();
  373. bSurrender->activate();
  374. bFlee->activate();
  375. bAutofight->activate();
  376. bSpell->activate();
  377. bWait->activate();
  378. bDefence->activate();
  379. if (attackingHero)
  380. attackingHero->activate();
  381. if (defendingHero)
  382. defendingHero->activate();
  383. for (auto hex : bfield)
  384. hex->activate();
  385. if (settings["battle"]["showQueue"].Bool())
  386. queue->activate();
  387. if (tacticsMode)
  388. {
  389. btactNext->activate();
  390. btactEnd->activate();
  391. }
  392. else
  393. {
  394. bConsoleUp->activate();
  395. bConsoleDown->activate();
  396. }
  397. LOCPLINT->cingconsole->activate();
  398. }
  399. void CBattleInterface::deactivate()
  400. {
  401. CIntObject::deactivate();
  402. bOptions->deactivate();
  403. bSurrender->deactivate();
  404. bFlee->deactivate();
  405. bAutofight->deactivate();
  406. bSpell->deactivate();
  407. bWait->deactivate();
  408. bDefence->deactivate();
  409. for (auto hex : bfield)
  410. hex->deactivate();
  411. if (attackingHero)
  412. attackingHero->deactivate();
  413. if (defendingHero)
  414. defendingHero->deactivate();
  415. if (settings["battle"]["showQueue"].Bool())
  416. queue->deactivate();
  417. if (tacticsMode)
  418. {
  419. btactNext->deactivate();
  420. btactEnd->deactivate();
  421. }
  422. else
  423. {
  424. bConsoleUp->deactivate();
  425. bConsoleDown->deactivate();
  426. }
  427. LOCPLINT->cingconsole->deactivate();
  428. }
  429. void CBattleInterface::keyPressed(const SDL_KeyboardEvent & key)
  430. {
  431. if(key.keysym.sym == SDLK_q && key.state == SDL_PRESSED)
  432. {
  433. if(settings["battle"]["showQueue"].Bool()) //hide queue
  434. hideQueue();
  435. else
  436. showQueue();
  437. }
  438. else if(key.keysym.sym == SDLK_f && key.state == SDL_PRESSED)
  439. {
  440. enterCreatureCastingMode();
  441. }
  442. else if(key.keysym.sym == SDLK_ESCAPE)
  443. {
  444. if(!battleActionsStarted)
  445. CCS->soundh->stopSound(battleIntroSoundChannel);
  446. else
  447. endCastingSpell();
  448. }
  449. }
  450. void CBattleInterface::mouseMoved(const SDL_MouseMotionEvent &sEvent)
  451. {
  452. auto hexItr = std::find_if(bfield.begin(), bfield.end(), [](std::shared_ptr<CClickableHex> hex)
  453. {
  454. return hex->hovered && hex->strictHovered;
  455. });
  456. handleHex(hexItr == bfield.end() ? -1 : (*hexItr)->myNumber, MOVE);
  457. }
  458. void CBattleInterface::setBattleCursor(const int myNumber)
  459. {
  460. const CClickableHex & hoveredHex = *bfield[myNumber];
  461. CCursorHandler *cursor = CCS->curh;
  462. const double subdividingAngle = 2.0*M_PI/6.0; // Divide a hex into six sectors.
  463. const double hexMidX = hoveredHex.pos.x + hoveredHex.pos.w/2.0;
  464. const double hexMidY = hoveredHex.pos.y + hoveredHex.pos.h/2.0;
  465. const double cursorHexAngle = M_PI - atan2(hexMidY - cursor->ypos, cursor->xpos - hexMidX) + subdividingAngle/2; //TODO: refactor this nightmare
  466. const double sector = fmod(cursorHexAngle/subdividingAngle, 6.0);
  467. const int zigzagCorrection = !((myNumber/GameConstants::BFIELD_WIDTH)%2); // Off-by-one correction needed to deal with the odd battlefield rows.
  468. std::vector<int> sectorCursor; // From left to bottom left.
  469. sectorCursor.push_back(8);
  470. sectorCursor.push_back(9);
  471. sectorCursor.push_back(10);
  472. sectorCursor.push_back(11);
  473. sectorCursor.push_back(12);
  474. sectorCursor.push_back(7);
  475. const bool doubleWide = activeStack->doubleWide();
  476. bool aboveAttackable = true, belowAttackable = true;
  477. // Exclude directions which cannot be attacked from.
  478. // Check to the left.
  479. if (myNumber%GameConstants::BFIELD_WIDTH <= 1 || !vstd::contains(occupyableHexes, myNumber - 1))
  480. {
  481. sectorCursor[0] = -1;
  482. }
  483. // Check top left, top right as well as above for 2-hex creatures.
  484. if (myNumber/GameConstants::BFIELD_WIDTH == 0)
  485. {
  486. sectorCursor[1] = -1;
  487. sectorCursor[2] = -1;
  488. aboveAttackable = false;
  489. }
  490. else
  491. {
  492. if (doubleWide)
  493. {
  494. bool attackRow[4] = {true, true, true, true};
  495. if (myNumber%GameConstants::BFIELD_WIDTH <= 1 || !vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH - 2 + zigzagCorrection))
  496. attackRow[0] = false;
  497. if (!vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection))
  498. attackRow[1] = false;
  499. if (!vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH + zigzagCorrection))
  500. attackRow[2] = false;
  501. if (myNumber%GameConstants::BFIELD_WIDTH >= GameConstants::BFIELD_WIDTH - 2 || !vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH + 1 + zigzagCorrection))
  502. attackRow[3] = false;
  503. if (!(attackRow[0] && attackRow[1]))
  504. sectorCursor[1] = -1;
  505. if (!(attackRow[1] && attackRow[2]))
  506. aboveAttackable = false;
  507. if (!(attackRow[2] && attackRow[3]))
  508. sectorCursor[2] = -1;
  509. }
  510. else
  511. {
  512. if (!vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection))
  513. sectorCursor[1] = -1;
  514. if (!vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH + zigzagCorrection))
  515. sectorCursor[2] = -1;
  516. }
  517. }
  518. // Check to the right.
  519. if (myNumber%GameConstants::BFIELD_WIDTH >= GameConstants::BFIELD_WIDTH - 2 || !vstd::contains(occupyableHexes, myNumber + 1))
  520. {
  521. sectorCursor[3] = -1;
  522. }
  523. // Check bottom right, bottom left as well as below for 2-hex creatures.
  524. if (myNumber/GameConstants::BFIELD_WIDTH == GameConstants::BFIELD_HEIGHT - 1)
  525. {
  526. sectorCursor[4] = -1;
  527. sectorCursor[5] = -1;
  528. belowAttackable = false;
  529. }
  530. else
  531. {
  532. if (doubleWide)
  533. {
  534. bool attackRow[4] = {true, true, true, true};
  535. if (myNumber%GameConstants::BFIELD_WIDTH <= 1 || !vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH - 2 + zigzagCorrection))
  536. attackRow[0] = false;
  537. if (!vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection))
  538. attackRow[1] = false;
  539. if (!vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH + zigzagCorrection))
  540. attackRow[2] = false;
  541. if (myNumber%GameConstants::BFIELD_WIDTH >= GameConstants::BFIELD_WIDTH - 2 || !vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH + 1 + zigzagCorrection))
  542. attackRow[3] = false;
  543. if (!(attackRow[0] && attackRow[1]))
  544. sectorCursor[5] = -1;
  545. if (!(attackRow[1] && attackRow[2]))
  546. belowAttackable = false;
  547. if (!(attackRow[2] && attackRow[3]))
  548. sectorCursor[4] = -1;
  549. }
  550. else
  551. {
  552. if (!vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH + zigzagCorrection))
  553. sectorCursor[4] = -1;
  554. if (!vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection))
  555. sectorCursor[5] = -1;
  556. }
  557. }
  558. // Determine index from sector.
  559. int cursorIndex;
  560. if (doubleWide)
  561. {
  562. sectorCursor.insert(sectorCursor.begin() + 5, belowAttackable ? 13 : -1);
  563. sectorCursor.insert(sectorCursor.begin() + 2, aboveAttackable ? 14 : -1);
  564. if (sector < 1.5)
  565. cursorIndex = static_cast<int>(sector);
  566. else if (sector >= 1.5 && sector < 2.5)
  567. cursorIndex = 2;
  568. else if (sector >= 2.5 && sector < 4.5)
  569. cursorIndex = (int) sector + 1;
  570. else if (sector >= 4.5 && sector < 5.5)
  571. cursorIndex = 6;
  572. else
  573. cursorIndex = (int) sector + 2;
  574. }
  575. else
  576. {
  577. cursorIndex = static_cast<int>(sector);
  578. }
  579. // Generally should NEVER happen, but to avoid the possibility of having endless loop below... [#1016]
  580. if (!vstd::contains_if (sectorCursor, [](int sc) { return sc != -1; }))
  581. {
  582. logGlobal->error("Error: for hex %d cannot find a hex to attack from!", myNumber);
  583. attackingHex = -1;
  584. return;
  585. }
  586. // Find the closest direction attackable, starting with the right one.
  587. // FIXME: Is this really how the original H3 client does it?
  588. int i = 0;
  589. while (sectorCursor[(cursorIndex + i)%sectorCursor.size()] == -1) //Why hast thou forsaken me?
  590. i = i <= 0 ? 1 - i : -i; // 0, 1, -1, 2, -2, 3, -3 etc..
  591. int index = (cursorIndex + i)%sectorCursor.size(); //hopefully we get elements from sectorCursor
  592. cursor->changeGraphic(ECursor::COMBAT, sectorCursor[index]);
  593. switch (index)
  594. {
  595. case 0:
  596. attackingHex = myNumber - 1; //left
  597. break;
  598. case 1:
  599. attackingHex = myNumber - GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection; //top left
  600. break;
  601. case 2:
  602. attackingHex = myNumber - GameConstants::BFIELD_WIDTH + zigzagCorrection; //top right
  603. break;
  604. case 3:
  605. attackingHex = myNumber + 1; //right
  606. break;
  607. case 4:
  608. attackingHex = myNumber + GameConstants::BFIELD_WIDTH + zigzagCorrection; //bottom right
  609. break;
  610. case 5:
  611. attackingHex = myNumber + GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection; //bottom left
  612. break;
  613. }
  614. BattleHex hex(attackingHex);
  615. if (!hex.isValid())
  616. attackingHex = -1;
  617. }
  618. void CBattleInterface::clickRight(tribool down, bool previousState)
  619. {
  620. if (!down)
  621. {
  622. endCastingSpell();
  623. }
  624. }
  625. void CBattleInterface::bOptionsf()
  626. {
  627. if (spellDestSelectMode) //we are casting a spell
  628. return;
  629. CCS->curh->changeGraphic(ECursor::ADVENTURE,0);
  630. Rect tempRect = genRect(431, 481, 160, 84);
  631. tempRect += pos.topLeft();
  632. GH.pushIntT<CBattleOptionsWindow>(tempRect, this);
  633. }
  634. void CBattleInterface::bSurrenderf()
  635. {
  636. if(spellDestSelectMode) //we are casting a spell
  637. return;
  638. int cost = curInt->cb->battleGetSurrenderCost();
  639. if(cost >= 0)
  640. {
  641. std::string enemyHeroName = curInt->cb->battleGetEnemyHero().name;
  642. if(enemyHeroName.empty())
  643. {
  644. logGlobal->warn("Surrender performed without enemy hero, should not happen!");
  645. enemyHeroName = "#ENEMY#";
  646. }
  647. std::string surrenderMessage = boost::str(boost::format(CGI->generaltexth->allTexts[32]) % enemyHeroName % cost); //%s states: "I will accept your surrender and grant you and your troops safe passage for the price of %d gold."
  648. curInt->showYesNoDialog(surrenderMessage, [this](){ reallySurrender(); }, nullptr);
  649. }
  650. }
  651. void CBattleInterface::bFleef()
  652. {
  653. if (spellDestSelectMode) //we are casting a spell
  654. return;
  655. if ( curInt->cb->battleCanFlee() )
  656. {
  657. CFunctionList<void()> ony = std::bind(&CBattleInterface::reallyFlee,this);
  658. curInt->showYesNoDialog(CGI->generaltexth->allTexts[28], ony, nullptr); //Are you sure you want to retreat?
  659. }
  660. else
  661. {
  662. std::vector<std::shared_ptr<CComponent>> comps;
  663. std::string heroName;
  664. //calculating fleeing hero's name
  665. if (attackingHeroInstance)
  666. if (attackingHeroInstance->tempOwner == curInt->cb->getMyColor())
  667. heroName = attackingHeroInstance->name;
  668. if (defendingHeroInstance)
  669. if (defendingHeroInstance->tempOwner == curInt->cb->getMyColor())
  670. heroName = defendingHeroInstance->name;
  671. //calculating text
  672. auto txt = boost::format(CGI->generaltexth->allTexts[340]) % heroName; //The Shackles of War are present. %s can not retreat!
  673. //printing message
  674. curInt->showInfoDialog(boost::to_string(txt), comps);
  675. }
  676. }
  677. void CBattleInterface::reallyFlee()
  678. {
  679. giveCommand(EActionType::RETREAT);
  680. CCS->curh->changeGraphic(ECursor::ADVENTURE, 0);
  681. }
  682. void CBattleInterface::reallySurrender()
  683. {
  684. if (curInt->cb->getResourceAmount(Res::GOLD) < curInt->cb->battleGetSurrenderCost())
  685. {
  686. curInt->showInfoDialog(CGI->generaltexth->allTexts[29]); //You don't have enough gold!
  687. }
  688. else
  689. {
  690. giveCommand(EActionType::SURRENDER);
  691. CCS->curh->changeGraphic(ECursor::ADVENTURE, 0);
  692. }
  693. }
  694. void CBattleInterface::bAutofightf()
  695. {
  696. if(spellDestSelectMode) //we are casting a spell
  697. return;
  698. //Stop auto-fight mode
  699. if(curInt->isAutoFightOn)
  700. {
  701. assert(curInt->autofightingAI);
  702. curInt->isAutoFightOn = false;
  703. logGlobal->trace("Stopping the autofight...");
  704. }
  705. else if(!curInt->autofightingAI)
  706. {
  707. curInt->isAutoFightOn = true;
  708. blockUI(true);
  709. auto ai = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
  710. ai->init(curInt->env, curInt->cb);
  711. ai->battleStart(army1, army2, int3(0,0,0), attackingHeroInstance, defendingHeroInstance, curInt->cb->battleGetMySide());
  712. curInt->autofightingAI = ai;
  713. curInt->cb->registerBattleInterface(ai);
  714. requestAutofightingAIToTakeAction();
  715. }
  716. }
  717. void CBattleInterface::bSpellf()
  718. {
  719. if (spellDestSelectMode) //we are casting a spell
  720. return;
  721. if (!myTurn)
  722. return;
  723. auto myHero = currentHero();
  724. if(!myHero)
  725. return;
  726. CCS->curh->changeGraphic(ECursor::ADVENTURE,0);
  727. ESpellCastProblem::ESpellCastProblem spellCastProblem = curInt->cb->battleCanCastSpell(myHero, spells::Mode::HERO);
  728. if(spellCastProblem == ESpellCastProblem::OK)
  729. {
  730. GH.pushIntT<CSpellWindow>(myHero, curInt.get());
  731. }
  732. else if (spellCastProblem == ESpellCastProblem::MAGIC_IS_BLOCKED)
  733. {
  734. //TODO: move to spell mechanics, add more information to spell cast problem
  735. //Handle Orb of Inhibition-like effects -> we want to display dialog with info, why casting is impossible
  736. auto blockingBonus = currentHero()->getBonusLocalFirst(Selector::type()(Bonus::BLOCK_ALL_MAGIC));
  737. if (!blockingBonus)
  738. return;
  739. if (blockingBonus->source == Bonus::ARTIFACT)
  740. {
  741. const int32_t artID = blockingBonus->sid;
  742. //If we have artifact, put name of our hero. Otherwise assume it's the enemy.
  743. //TODO check who *really* is source of bonus
  744. std::string heroName = myHero->hasArt(artID) ? myHero->name : enemyHero().name;
  745. //%s wields the %s, an ancient artifact which creates a p dead to all magic.
  746. LOCPLINT->showInfoDialog(boost::str(boost::format(CGI->generaltexth->allTexts[683])
  747. % heroName % CGI->artifacts()->getByIndex(artID)->getName()));
  748. }
  749. }
  750. }
  751. void CBattleInterface::bWaitf()
  752. {
  753. if (spellDestSelectMode) //we are casting a spell
  754. return;
  755. if (activeStack != nullptr)
  756. giveCommand(EActionType::WAIT);
  757. }
  758. void CBattleInterface::bDefencef()
  759. {
  760. if (spellDestSelectMode) //we are casting a spell
  761. return;
  762. if (activeStack != nullptr)
  763. giveCommand(EActionType::DEFEND);
  764. }
  765. void CBattleInterface::bConsoleUpf()
  766. {
  767. if (spellDestSelectMode) //we are casting a spell
  768. return;
  769. console->scrollUp();
  770. }
  771. void CBattleInterface::bConsoleDownf()
  772. {
  773. if (spellDestSelectMode) //we are casting a spell
  774. return;
  775. console->scrollDown();
  776. }
  777. void CBattleInterface::unitAdded(const CStack * stack)
  778. {
  779. creDir[stack->ID] = stack->side == BattleSide::ATTACKER; // must be set before getting stack position
  780. Point coords = CClickableHex::getXYUnitAnim(stack->getPosition(), stack, this);
  781. if(stack->initialPosition < 0) //turret
  782. {
  783. assert(siegeController);
  784. const CCreature *turretCreature = siegeController->turretCreature();
  785. creAnims[stack->ID] = AnimationControls::getAnimation(turretCreature);
  786. creAnims[stack->ID]->pos.h = 225;
  787. coords = siegeController->turretCreaturePosition(stack->initialPosition);
  788. }
  789. else
  790. {
  791. creAnims[stack->ID] = AnimationControls::getAnimation(stack->getCreature());
  792. creAnims[stack->ID]->onAnimationReset += std::bind(&onAnimationFinished, stack, creAnims[stack->ID]);
  793. creAnims[stack->ID]->pos.h = creAnims[stack->ID]->getHeight();
  794. }
  795. creAnims[stack->ID]->pos.x = coords.x;
  796. creAnims[stack->ID]->pos.y = coords.y;
  797. creAnims[stack->ID]->pos.w = creAnims[stack->ID]->getWidth();
  798. creAnims[stack->ID]->setType(CCreatureAnim::HOLDING);
  799. //loading projectiles for units
  800. if(stack->isShooter())
  801. {
  802. projectilesController->initStackProjectile(stack);
  803. }
  804. }
  805. void CBattleInterface::stackRemoved(uint32_t stackID)
  806. {
  807. if (activeStack != nullptr)
  808. {
  809. if (activeStack->ID == stackID)
  810. {
  811. BattleAction *action = new BattleAction();
  812. action->side = defendingHeroInstance ? (curInt->playerID == defendingHeroInstance->tempOwner) : false;
  813. action->actionType = EActionType::CANCEL;
  814. action->stackNumber = activeStack->ID;
  815. givenCommand.setn(action);
  816. setActiveStack(nullptr);
  817. }
  818. }
  819. //todo: ensure that ghost stack animation has fadeout effect
  820. redrawBackgroundWithHexes(activeStack);
  821. queue->update();
  822. }
  823. void CBattleInterface::stackActivated(const CStack *stack) //TODO: check it all before game state is changed due to abilities
  824. {
  825. stackToActivate = stack;
  826. waitForAnims();
  827. if (stackToActivate) //during waiting stack may have gotten activated through show
  828. activateStack();
  829. }
  830. void CBattleInterface::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  831. {
  832. addNewAnim(new CMovementAnimation(this, stack, destHex, distance));
  833. waitForAnims();
  834. }
  835. void CBattleInterface::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  836. {
  837. for(auto & attackedInfo : attackedInfos)
  838. {
  839. //if (!attackedInfo.cloneKilled) //FIXME: play dead animation for cloned creature before it vanishes
  840. addNewAnim(new CDefenceAnimation(attackedInfo, this));
  841. if(attackedInfo.rebirth)
  842. {
  843. displayEffect(50, attackedInfo.defender->getPosition()); //TODO: play reverse death animation
  844. CCS->soundh->playSound(soundBase::RESURECT);
  845. }
  846. }
  847. waitForAnims();
  848. std::array<int, 2> killedBySide = {0, 0};
  849. int targets = 0;
  850. for(const StackAttackedInfo & attackedInfo : attackedInfos)
  851. {
  852. ++targets;
  853. ui8 side = attackedInfo.defender->side;
  854. killedBySide.at(side) += attackedInfo.amountKilled;
  855. }
  856. for(ui8 side = 0; side < 2; side++)
  857. {
  858. if(killedBySide.at(side) > killedBySide.at(1-side))
  859. setHeroAnimation(side, 2);
  860. else if(killedBySide.at(side) < killedBySide.at(1-side))
  861. setHeroAnimation(side, 3);
  862. }
  863. for (auto & attackedInfo : attackedInfos)
  864. {
  865. if (attackedInfo.rebirth)
  866. creAnims[attackedInfo.defender->ID]->setType(CCreatureAnim::HOLDING);
  867. if (attackedInfo.cloneKilled)
  868. stackRemoved(attackedInfo.defender->ID);
  869. }
  870. }
  871. void CBattleInterface::stackAttacking( const CStack *attacker, BattleHex dest, const CStack *attacked, bool shooting )
  872. {
  873. if (shooting)
  874. {
  875. addNewAnim(new CShootingAnimation(this, attacker, dest, attacked));
  876. }
  877. else
  878. {
  879. addNewAnim(new CMeleeAttackAnimation(this, attacker, dest, attacked));
  880. }
  881. //waitForAnims();
  882. }
  883. void CBattleInterface::newRoundFirst( int round )
  884. {
  885. waitForAnims();
  886. }
  887. void CBattleInterface::newRound(int number)
  888. {
  889. console->addText(CGI->generaltexth->allTexts[412]);
  890. }
  891. void CBattleInterface::giveCommand(EActionType action, BattleHex tile, si32 additional)
  892. {
  893. const CStack * actor = nullptr;
  894. if(action != EActionType::HERO_SPELL && action != EActionType::RETREAT && action != EActionType::SURRENDER)
  895. {
  896. actor = activeStack;
  897. }
  898. auto side = curInt->cb->playerToSide(curInt->playerID);
  899. if(!side)
  900. {
  901. logGlobal->error("Player %s is not in battle", curInt->playerID.getStr());
  902. return;
  903. }
  904. auto ba = new BattleAction(); //is deleted in CPlayerInterface::activeStack()
  905. ba->side = side.get();
  906. ba->actionType = action;
  907. ba->aimToHex(tile);
  908. ba->actionSubtype = additional;
  909. sendCommand(ba, actor);
  910. }
  911. void CBattleInterface::sendCommand(BattleAction *& command, const CStack * actor)
  912. {
  913. command->stackNumber = actor ? actor->unitId() : ((command->side == BattleSide::ATTACKER) ? -1 : -2);
  914. if(!tacticsMode)
  915. {
  916. logGlobal->trace("Setting command for %s", (actor ? actor->nodeName() : "hero"));
  917. myTurn = false;
  918. setActiveStack(nullptr);
  919. givenCommand.setn(command);
  920. }
  921. else
  922. {
  923. curInt->cb->battleMakeTacticAction(command);
  924. vstd::clear_pointer(command);
  925. setActiveStack(nullptr);
  926. //next stack will be activated when action ends
  927. }
  928. }
  929. bool CBattleInterface::isTileAttackable(const BattleHex & number) const
  930. {
  931. for (auto & elem : occupyableHexes)
  932. {
  933. if (BattleHex::mutualPosition(elem, number) != -1 || elem == number)
  934. return true;
  935. }
  936. return false;
  937. }
  938. const CGHeroInstance * CBattleInterface::getActiveHero()
  939. {
  940. const CStack *attacker = activeStack;
  941. if(!attacker)
  942. {
  943. return nullptr;
  944. }
  945. if(attacker->side == BattleSide::ATTACKER)
  946. {
  947. return attackingHeroInstance;
  948. }
  949. return defendingHeroInstance;
  950. }
  951. void CBattleInterface::hexLclicked(int whichOne)
  952. {
  953. handleHex(whichOne, LCLICK);
  954. }
  955. void CBattleInterface::stackIsCatapulting(const CatapultAttack & ca)
  956. {
  957. if (siegeController)
  958. siegeController->stackIsCatapulting(ca);
  959. }
  960. void CBattleInterface::gateStateChanged(const EGateState state)
  961. {
  962. if (siegeController)
  963. siegeController->gateStateChanged(state);
  964. }
  965. void CBattleInterface::battleFinished(const BattleResult& br)
  966. {
  967. bresult = &br;
  968. {
  969. auto unlockPim = vstd::makeUnlockGuard(*CPlayerInterface::pim);
  970. animsAreDisplayed.waitUntil(false);
  971. }
  972. setActiveStack(nullptr);
  973. displayBattleFinished();
  974. }
  975. void CBattleInterface::displayBattleFinished()
  976. {
  977. CCS->curh->changeGraphic(ECursor::ADVENTURE,0);
  978. if(settings["session"]["spectate"].Bool() && settings["session"]["spectate-skip-battle-result"].Bool())
  979. {
  980. close();
  981. return;
  982. }
  983. GH.pushInt(std::make_shared<CBattleResultWindow>(*bresult, *(this->curInt)));
  984. curInt->waitWhileDialog(); // Avoid freeze when AI end turn after battle. Check bug #1897
  985. CPlayerInterface::battleInt = nullptr;
  986. }
  987. void CBattleInterface::spellCast(const BattleSpellCast * sc)
  988. {
  989. const SpellID spellID = sc->spellID;
  990. const CSpell * spell = spellID.toSpell();
  991. if(!spell)
  992. return;
  993. const std::string & castSoundPath = spell->getCastSound();
  994. if (!castSoundPath.empty())
  995. CCS->soundh->playSound(castSoundPath);
  996. const auto casterStackID = sc->casterStack;
  997. const CStack * casterStack = nullptr;
  998. if(casterStackID >= 0)
  999. {
  1000. casterStack = curInt->cb->battleGetStackByID(casterStackID);
  1001. }
  1002. Point srccoord = (sc->side ? Point(770, 60) : Point(30, 60)) + pos; //hero position by default
  1003. {
  1004. if(casterStack != nullptr)
  1005. {
  1006. srccoord = CClickableHex::getXYUnitAnim(casterStack->getPosition(), casterStack, this);
  1007. srccoord.x += 250;
  1008. srccoord.y += 240;
  1009. }
  1010. }
  1011. if(casterStack != nullptr && sc->activeCast)
  1012. {
  1013. //todo: custom cast animation for hero
  1014. displaySpellCast(spellID, casterStack->getPosition());
  1015. addNewAnim(new CCastAnimation(this, casterStack, sc->tile, curInt->cb->battleGetStackByPos(sc->tile)));
  1016. }
  1017. waitForAnims(); //wait for cast animation
  1018. //playing projectile animation
  1019. if (sc->tile.isValid())
  1020. {
  1021. Point destcoord = CClickableHex::getXYUnitAnim(sc->tile, curInt->cb->battleGetStackByPos(sc->tile), this); //position attacked by projectile
  1022. destcoord.x += 250; destcoord.y += 240;
  1023. //animation angle
  1024. double angle = atan2(static_cast<double>(destcoord.x - srccoord.x), static_cast<double>(destcoord.y - srccoord.y));
  1025. bool Vflip = (angle < 0);
  1026. if (Vflip)
  1027. angle = -angle;
  1028. std::string animToDisplay = spell->animationInfo.selectProjectile(angle);
  1029. if(!animToDisplay.empty())
  1030. {
  1031. //TODO: calculate inside CEffectAnimation
  1032. std::shared_ptr<CAnimation> tmp = std::make_shared<CAnimation>(animToDisplay);
  1033. tmp->load(0, 0);
  1034. auto first = tmp->getImage(0, 0);
  1035. //displaying animation
  1036. double diffX = (destcoord.x - srccoord.x)*(destcoord.x - srccoord.x);
  1037. double diffY = (destcoord.y - srccoord.y)*(destcoord.y - srccoord.y);
  1038. double distance = sqrt(diffX + diffY);
  1039. int steps = static_cast<int>(distance / AnimationControls::getSpellEffectSpeed() + 1);
  1040. int dx = (destcoord.x - srccoord.x - first->width())/steps;
  1041. int dy = (destcoord.y - srccoord.y - first->height())/steps;
  1042. addNewAnim(new CEffectAnimation(this, animToDisplay, srccoord.x, srccoord.y, dx, dy, Vflip));
  1043. }
  1044. }
  1045. waitForAnims(); //wait for projectile animation
  1046. displaySpellHit(spellID, sc->tile);
  1047. //queuing affect animation
  1048. for(auto & elem : sc->affectedCres)
  1049. {
  1050. auto stack = curInt->cb->battleGetStackByID(elem, false);
  1051. if(stack)
  1052. displaySpellEffect(spellID, stack->getPosition());
  1053. }
  1054. //queuing additional animation
  1055. for(auto & elem : sc->customEffects)
  1056. {
  1057. auto stack = curInt->cb->battleGetStackByID(elem.stack, false);
  1058. if(stack)
  1059. displayEffect(elem.effect, stack->getPosition());
  1060. }
  1061. waitForAnims();
  1062. //mana absorption
  1063. if (sc->manaGained > 0)
  1064. {
  1065. Point leftHero = Point(15, 30) + pos;
  1066. Point rightHero = Point(755, 30) + pos;
  1067. addNewAnim(new CEffectAnimation(this, sc->side ? "SP07_A.DEF" : "SP07_B.DEF", leftHero.x, leftHero.y, 0, 0, false));
  1068. addNewAnim(new CEffectAnimation(this, sc->side ? "SP07_B.DEF" : "SP07_A.DEF", rightHero.x, rightHero.y, 0, 0, false));
  1069. }
  1070. }
  1071. void CBattleInterface::battleStacksEffectsSet(const SetStackEffect & sse)
  1072. {
  1073. if(activeStack != nullptr)
  1074. redrawBackgroundWithHexes(activeStack);
  1075. }
  1076. void CBattleInterface::setHeroAnimation(ui8 side, int phase)
  1077. {
  1078. if(side == BattleSide::ATTACKER)
  1079. {
  1080. if(attackingHero)
  1081. attackingHero->setPhase(phase);
  1082. }
  1083. else
  1084. {
  1085. if(defendingHero)
  1086. defendingHero->setPhase(phase);
  1087. }
  1088. }
  1089. void CBattleInterface::castThisSpell(SpellID spellID)
  1090. {
  1091. spellToCast = std::make_shared<BattleAction>();
  1092. spellToCast->actionType = EActionType::HERO_SPELL;
  1093. spellToCast->actionSubtype = spellID; //spell number
  1094. spellToCast->stackNumber = (attackingHeroInstance->tempOwner == curInt->playerID) ? -1 : -2;
  1095. spellToCast->side = defendingHeroInstance ? (curInt->playerID == defendingHeroInstance->tempOwner) : false;
  1096. spellDestSelectMode = true;
  1097. creatureCasting = false;
  1098. //choosing possible targets
  1099. const CGHeroInstance *castingHero = (attackingHeroInstance->tempOwner == curInt->playerID) ? attackingHeroInstance : defendingHeroInstance;
  1100. assert(castingHero); // code below assumes non-null hero
  1101. sp = spellID.toSpell();
  1102. PossiblePlayerBattleAction spellSelMode = curInt->cb->getCasterAction(sp, castingHero, spells::Mode::HERO);
  1103. if (spellSelMode == PossiblePlayerBattleAction::NO_LOCATION) //user does not have to select location
  1104. {
  1105. spellToCast->aimToHex(BattleHex::INVALID);
  1106. curInt->cb->battleMakeAction(spellToCast.get());
  1107. endCastingSpell();
  1108. }
  1109. else
  1110. {
  1111. possibleActions.clear();
  1112. possibleActions.push_back (spellSelMode); //only this one action can be performed at the moment
  1113. GH.fakeMouseMove();//update cursor
  1114. }
  1115. }
  1116. void CBattleInterface::displayBattleLog(const std::vector<MetaString> & battleLog)
  1117. {
  1118. for(const auto & line : battleLog)
  1119. {
  1120. std::string formatted = line.toString();
  1121. boost::algorithm::trim(formatted);
  1122. if(!console->addText(formatted))
  1123. logGlobal->warn("Too long battle log line");
  1124. }
  1125. }
  1126. void CBattleInterface::displayCustomEffects(const std::vector<CustomEffectInfo> & customEffects)
  1127. {
  1128. for(const CustomEffectInfo & one : customEffects)
  1129. {
  1130. if(one.sound != 0)
  1131. CCS->soundh->playSound(soundBase::soundID(one.sound));
  1132. const CStack * s = curInt->cb->battleGetStackByID(one.stack, false);
  1133. if(s && one.effect != 0)
  1134. displayEffect(one.effect, s->getPosition());
  1135. }
  1136. }
  1137. void CBattleInterface::displayEffect(ui32 effect, BattleHex destTile)
  1138. {
  1139. std::string customAnim = graphics->battleACToDef[effect][0];
  1140. addNewAnim(new CEffectAnimation(this, customAnim, destTile));
  1141. }
  1142. void CBattleInterface::displaySpellAnimationQueue(const CSpell::TAnimationQueue & q, BattleHex destinationTile)
  1143. {
  1144. for(const CSpell::TAnimation & animation : q)
  1145. {
  1146. if(animation.pause > 0)
  1147. addNewAnim(new CDummyAnimation(this, animation.pause));
  1148. else
  1149. addNewAnim(new CEffectAnimation(this, animation.resourceName, destinationTile, false, animation.verticalPosition == VerticalPosition::BOTTOM));
  1150. }
  1151. }
  1152. void CBattleInterface::displaySpellCast(SpellID spellID, BattleHex destinationTile)
  1153. {
  1154. const CSpell * spell = spellID.toSpell();
  1155. if(spell)
  1156. displaySpellAnimationQueue(spell->animationInfo.cast, destinationTile);
  1157. }
  1158. void CBattleInterface::displaySpellEffect(SpellID spellID, BattleHex destinationTile)
  1159. {
  1160. const CSpell *spell = spellID.toSpell();
  1161. if(spell)
  1162. displaySpellAnimationQueue(spell->animationInfo.affect, destinationTile);
  1163. }
  1164. void CBattleInterface::displaySpellHit(SpellID spellID, BattleHex destinationTile)
  1165. {
  1166. const CSpell * spell = spellID.toSpell();
  1167. if(spell)
  1168. displaySpellAnimationQueue(spell->animationInfo.hit, destinationTile);
  1169. }
  1170. void CBattleInterface::battleTriggerEffect(const BattleTriggerEffect & bte)
  1171. {
  1172. const CStack * stack = curInt->cb->battleGetStackByID(bte.stackID);
  1173. if(!stack)
  1174. {
  1175. logGlobal->error("Invalid stack ID %d", bte.stackID);
  1176. return;
  1177. }
  1178. //don't show animation when no HP is regenerated
  1179. switch(bte.effect)
  1180. {
  1181. //TODO: move to bonus type handler
  1182. case Bonus::HP_REGENERATION:
  1183. displayEffect(74, stack->getPosition());
  1184. CCS->soundh->playSound(soundBase::REGENER);
  1185. break;
  1186. case Bonus::MANA_DRAIN:
  1187. displayEffect(77, stack->getPosition());
  1188. CCS->soundh->playSound(soundBase::MANADRAI);
  1189. break;
  1190. case Bonus::POISON:
  1191. displayEffect(67, stack->getPosition());
  1192. CCS->soundh->playSound(soundBase::POISON);
  1193. break;
  1194. case Bonus::FEAR:
  1195. displayEffect(15, stack->getPosition());
  1196. CCS->soundh->playSound(soundBase::FEAR);
  1197. break;
  1198. case Bonus::MORALE:
  1199. {
  1200. std::string hlp = CGI->generaltexth->allTexts[33];
  1201. boost::algorithm::replace_first(hlp,"%s",(stack->getName()));
  1202. displayEffect(20,stack->getPosition());
  1203. CCS->soundh->playSound(soundBase::GOODMRLE);
  1204. console->addText(hlp);
  1205. break;
  1206. }
  1207. default:
  1208. return;
  1209. }
  1210. //waitForAnims(); //fixme: freezes game :?
  1211. }
  1212. void CBattleInterface::setAnimSpeed(int set)
  1213. {
  1214. Settings speed = settings.write["battle"]["animationSpeed"];
  1215. speed->Float() = float(set) / 100;
  1216. }
  1217. int CBattleInterface::getAnimSpeed() const
  1218. {
  1219. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-battle-speed"].isNull())
  1220. return static_cast<int>(vstd::round(settings["session"]["spectate-battle-speed"].Float() *100));
  1221. return static_cast<int>(vstd::round(settings["battle"]["animationSpeed"].Float() *100));
  1222. }
  1223. CPlayerInterface *CBattleInterface::getCurrentPlayerInterface() const
  1224. {
  1225. return curInt.get();
  1226. }
  1227. bool CBattleInterface::shouldRotate(const CStack * stack, const BattleHex & oldPos, const BattleHex & nextHex)
  1228. {
  1229. Point begPosition = CClickableHex::getXYUnitAnim(oldPos,stack, this);
  1230. Point endPosition = CClickableHex::getXYUnitAnim(nextHex, stack, this);
  1231. if((begPosition.x > endPosition.x) && creDir[stack->ID])
  1232. return true;
  1233. else if((begPosition.x < endPosition.x) && !creDir[stack->ID])
  1234. return true;
  1235. return false;
  1236. }
  1237. void CBattleInterface::setActiveStack(const CStack *stack)
  1238. {
  1239. if (activeStack) // update UI
  1240. creAnims[activeStack->ID]->setBorderColor(AnimationControls::getNoBorder());
  1241. activeStack = stack;
  1242. if (activeStack) // update UI
  1243. creAnims[activeStack->ID]->setBorderColor(AnimationControls::getGoldBorder());
  1244. blockUI(activeStack == nullptr);
  1245. }
  1246. void CBattleInterface::setHoveredStack(const CStack *stack)
  1247. {
  1248. if (mouseHoveredStack)
  1249. creAnims[mouseHoveredStack->ID]->setBorderColor(AnimationControls::getNoBorder());
  1250. // stack must be alive and not active (which uses gold border instead)
  1251. if (stack && stack->alive() && stack != activeStack)
  1252. {
  1253. mouseHoveredStack = stack;
  1254. if (mouseHoveredStack)
  1255. {
  1256. creAnims[mouseHoveredStack->ID]->setBorderColor(AnimationControls::getBlueBorder());
  1257. if (creAnims[mouseHoveredStack->ID]->framesInGroup(CCreatureAnim::MOUSEON) > 0)
  1258. creAnims[mouseHoveredStack->ID]->playOnce(CCreatureAnim::MOUSEON);
  1259. }
  1260. }
  1261. else
  1262. mouseHoveredStack = nullptr;
  1263. }
  1264. void CBattleInterface::activateStack()
  1265. {
  1266. if(!battleActionsStarted)
  1267. return; //"show" function should re-call this function
  1268. myTurn = true;
  1269. if (!!attackerInt && defenderInt) //hotseat -> need to pick which interface "takes over" as active
  1270. curInt = attackerInt->playerID == stackToActivate->owner ? attackerInt : defenderInt;
  1271. setActiveStack(stackToActivate);
  1272. stackToActivate = nullptr;
  1273. const CStack * s = activeStack;
  1274. if(!s)
  1275. return;
  1276. queue->update();
  1277. redrawBackgroundWithHexes(activeStack);
  1278. //set casting flag to true if creature can use it to not check it every time
  1279. const auto spellcaster = s->getBonusLocalFirst(Selector::type()(Bonus::SPELLCASTER)),
  1280. randomSpellcaster = s->getBonusLocalFirst(Selector::type()(Bonus::RANDOM_SPELLCASTER));
  1281. if(s->canCast() && (spellcaster || randomSpellcaster))
  1282. {
  1283. stackCanCastSpell = true;
  1284. if(randomSpellcaster)
  1285. creatureSpellToCast = -1; //spell will be set later on cast
  1286. else
  1287. creatureSpellToCast = curInt->cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), s, CBattleInfoCallback::RANDOM_AIMED); //faerie dragon can cast only one spell until their next move
  1288. //TODO: what if creature can cast BOTH random genie spell and aimed spell?
  1289. //TODO: faerie dragon type spell should be selected by server
  1290. }
  1291. else
  1292. {
  1293. stackCanCastSpell = false;
  1294. creatureSpellToCast = -1;
  1295. }
  1296. possibleActions = getPossibleActionsForStack(s);
  1297. GH.fakeMouseMove();
  1298. }
  1299. void CBattleInterface::endCastingSpell()
  1300. {
  1301. if(spellDestSelectMode)
  1302. {
  1303. spellToCast.reset();
  1304. sp = nullptr;
  1305. spellDestSelectMode = false;
  1306. CCS->curh->changeGraphic(ECursor::COMBAT, ECursor::COMBAT_POINTER);
  1307. if(activeStack)
  1308. {
  1309. possibleActions = getPossibleActionsForStack(activeStack); //restore actions after they were cleared
  1310. myTurn = true;
  1311. }
  1312. }
  1313. else
  1314. {
  1315. if(activeStack)
  1316. {
  1317. possibleActions = getPossibleActionsForStack(activeStack);
  1318. GH.fakeMouseMove();
  1319. }
  1320. }
  1321. }
  1322. void CBattleInterface::enterCreatureCastingMode()
  1323. {
  1324. //silently check for possible errors
  1325. if (!myTurn)
  1326. return;
  1327. if (tacticsMode)
  1328. return;
  1329. //hero is casting a spell
  1330. if (spellDestSelectMode)
  1331. return;
  1332. if (!activeStack)
  1333. return;
  1334. if (!stackCanCastSpell)
  1335. return;
  1336. //random spellcaster
  1337. if (creatureSpellToCast == -1)
  1338. return;
  1339. if (vstd::contains(possibleActions, PossiblePlayerBattleAction::NO_LOCATION))
  1340. {
  1341. const spells::Caster * caster = activeStack;
  1342. const CSpell * spell = SpellID(creatureSpellToCast).toSpell();
  1343. spells::Target target;
  1344. target.emplace_back();
  1345. spells::BattleCast cast(curInt->cb.get(), caster, spells::Mode::CREATURE_ACTIVE, spell);
  1346. auto m = spell->battleMechanics(&cast);
  1347. spells::detail::ProblemImpl ignored;
  1348. const bool isCastingPossible = m->canBeCastAt(target, ignored);
  1349. if (isCastingPossible)
  1350. {
  1351. myTurn = false;
  1352. giveCommand(EActionType::MONSTER_SPELL, BattleHex::INVALID, creatureSpellToCast);
  1353. selectedStack = nullptr;
  1354. CCS->curh->changeGraphic(ECursor::COMBAT, ECursor::COMBAT_POINTER);
  1355. }
  1356. }
  1357. else
  1358. {
  1359. possibleActions = getPossibleActionsForStack(activeStack);
  1360. auto actionFilterPredicate = [](const PossiblePlayerBattleAction x)
  1361. {
  1362. return (x != PossiblePlayerBattleAction::ANY_LOCATION) && (x != PossiblePlayerBattleAction::NO_LOCATION) &&
  1363. (x != PossiblePlayerBattleAction::FREE_LOCATION) && (x != PossiblePlayerBattleAction::AIMED_SPELL_CREATURE) &&
  1364. (x != PossiblePlayerBattleAction::OBSTACLE);
  1365. };
  1366. vstd::erase_if(possibleActions, actionFilterPredicate);
  1367. GH.fakeMouseMove();
  1368. }
  1369. }
  1370. std::vector<PossiblePlayerBattleAction> CBattleInterface::getPossibleActionsForStack(const CStack *stack)
  1371. {
  1372. BattleClientInterfaceData data; //hard to get rid of these things so for now they're required data to pass
  1373. data.creatureSpellToCast = creatureSpellToCast;
  1374. data.tacticsMode = tacticsMode;
  1375. auto allActions = curInt->cb->getClientActionsForStack(stack, data);
  1376. return std::vector<PossiblePlayerBattleAction>(allActions);
  1377. }
  1378. void CBattleInterface::reorderPossibleActionsPriority(const CStack * stack, MouseHoveredHexContext context)
  1379. {
  1380. if(tacticsMode || possibleActions.empty()) return; //this function is not supposed to be called in tactics mode or before getPossibleActionsForStack
  1381. auto assignPriority = [&](PossiblePlayerBattleAction const & item) -> uint8_t //large lambda assigning priority which would have to be part of possibleActions without it
  1382. {
  1383. switch(item)
  1384. {
  1385. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  1386. case PossiblePlayerBattleAction::ANY_LOCATION:
  1387. case PossiblePlayerBattleAction::NO_LOCATION:
  1388. case PossiblePlayerBattleAction::FREE_LOCATION:
  1389. case PossiblePlayerBattleAction::OBSTACLE:
  1390. if(!stack->hasBonusOfType(Bonus::NO_SPELLCAST_BY_DEFAULT) && context == MouseHoveredHexContext::OCCUPIED_HEX)
  1391. return 1;
  1392. else
  1393. return 100;//bottom priority
  1394. break;
  1395. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
  1396. return 2; break;
  1397. case PossiblePlayerBattleAction::RISE_DEMONS:
  1398. return 3; break;
  1399. case PossiblePlayerBattleAction::SHOOT:
  1400. return 4; break;
  1401. case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
  1402. return 5; break;
  1403. case PossiblePlayerBattleAction::ATTACK:
  1404. return 6; break;
  1405. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  1406. return 7; break;
  1407. case PossiblePlayerBattleAction::MOVE_STACK:
  1408. return 8; break;
  1409. case PossiblePlayerBattleAction::CATAPULT:
  1410. return 9; break;
  1411. case PossiblePlayerBattleAction::HEAL:
  1412. return 10; break;
  1413. default:
  1414. return 200; break;
  1415. }
  1416. };
  1417. auto comparer = [&](PossiblePlayerBattleAction const & lhs, PossiblePlayerBattleAction const & rhs)
  1418. {
  1419. return assignPriority(lhs) > assignPriority(rhs);
  1420. };
  1421. std::make_heap(possibleActions.begin(), possibleActions.end(), comparer);
  1422. }
  1423. void CBattleInterface::endAction(const BattleAction* action)
  1424. {
  1425. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  1426. if(action->actionType == EActionType::HERO_SPELL)
  1427. setHeroAnimation(action->side, 0);
  1428. //check if we should reverse stacks
  1429. //for some strange reason, it's not enough
  1430. TStacks stacks = curInt->cb->battleGetStacks(CBattleCallback::MINE_AND_ENEMY);
  1431. for (const CStack *s : stacks)
  1432. {
  1433. if (s && creDir[s->ID] != (s->side == BattleSide::ATTACKER) && s->alive()
  1434. && creAnims[s->ID]->isIdle())
  1435. {
  1436. addNewAnim(new CReverseAnimation(this, s, s->getPosition(), false));
  1437. }
  1438. }
  1439. queue->update();
  1440. if (tacticsMode) //stack ended movement in tactics phase -> select the next one
  1441. bTacticNextStack(stack);
  1442. if(action->actionType == EActionType::HERO_SPELL) //we have activated next stack after sending request that has been just realized -> blockmap due to movement has changed
  1443. redrawBackgroundWithHexes(activeStack);
  1444. if (activeStack && !animsAreDisplayed.get() && pendingAnims.empty() && !active)
  1445. {
  1446. logGlobal->warn("Something wrong... interface was deactivated but there is no animation. Reactivating...");
  1447. blockUI(false);
  1448. }
  1449. else
  1450. {
  1451. // block UI if no active stack (e.g. enemy turn);
  1452. blockUI(activeStack == nullptr);
  1453. }
  1454. }
  1455. void CBattleInterface::hideQueue()
  1456. {
  1457. Settings showQueue = settings.write["battle"]["showQueue"];
  1458. showQueue->Bool() = false;
  1459. queue->deactivate();
  1460. if (!queue->embedded)
  1461. {
  1462. moveBy(Point(0, -queue->pos.h / 2));
  1463. GH.totalRedraw();
  1464. }
  1465. }
  1466. void CBattleInterface::showQueue()
  1467. {
  1468. Settings showQueue = settings.write["battle"]["showQueue"];
  1469. showQueue->Bool() = true;
  1470. queue->activate();
  1471. if (!queue->embedded)
  1472. {
  1473. moveBy(Point(0, +queue->pos.h / 2));
  1474. GH.totalRedraw();
  1475. }
  1476. }
  1477. void CBattleInterface::blockUI(bool on)
  1478. {
  1479. bool canCastSpells = false;
  1480. auto hero = curInt->cb->battleGetMyHero();
  1481. if(hero)
  1482. {
  1483. ESpellCastProblem::ESpellCastProblem spellcastingProblem = curInt->cb->battleCanCastSpell(hero, spells::Mode::HERO);
  1484. //if magic is blocked, we leave button active, so the message can be displayed after button click
  1485. canCastSpells = spellcastingProblem == ESpellCastProblem::OK || spellcastingProblem == ESpellCastProblem::MAGIC_IS_BLOCKED;
  1486. }
  1487. bool canWait = activeStack ? !activeStack->waitedThisTurn : false;
  1488. bOptions->block(on);
  1489. bFlee->block(on || !curInt->cb->battleCanFlee());
  1490. bSurrender->block(on || curInt->cb->battleGetSurrenderCost() < 0);
  1491. // block only if during enemy turn and auto-fight is off
  1492. // otherwise - crash on accessing non-exisiting active stack
  1493. bAutofight->block(!curInt->isAutoFightOn && !activeStack);
  1494. if (tacticsMode && btactEnd && btactNext)
  1495. {
  1496. btactNext->block(on);
  1497. btactEnd->block(on);
  1498. }
  1499. else
  1500. {
  1501. bConsoleUp->block(on);
  1502. bConsoleDown->block(on);
  1503. }
  1504. bSpell->block(on || tacticsMode || !canCastSpells);
  1505. bWait->block(on || tacticsMode || !canWait);
  1506. bDefence->block(on || tacticsMode);
  1507. }
  1508. void CBattleInterface::startAction(const BattleAction* action)
  1509. {
  1510. //setActiveStack(nullptr);
  1511. setHoveredStack(nullptr);
  1512. blockUI(true);
  1513. if(action->actionType == EActionType::END_TACTIC_PHASE)
  1514. {
  1515. SDL_FreeSurface(menu);
  1516. menu = BitmapHandler::loadBitmap("CBAR.bmp");
  1517. graphics->blueToPlayersAdv(menu, curInt->playerID);
  1518. return;
  1519. }
  1520. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  1521. if (stack)
  1522. {
  1523. queue->update();
  1524. }
  1525. else
  1526. {
  1527. assert(action->actionType == EActionType::HERO_SPELL); //only cast spell is valid action without acting stack number
  1528. }
  1529. auto actionTarget = action->getTarget(curInt->cb.get());
  1530. if(action->actionType == EActionType::WALK
  1531. || (action->actionType == EActionType::WALK_AND_ATTACK && actionTarget.at(0).hexValue != stack->getPosition()))
  1532. {
  1533. assert(stack);
  1534. moveStarted = true;
  1535. if (creAnims[action->stackNumber]->framesInGroup(CCreatureAnim::MOVE_START))
  1536. {
  1537. pendingAnims.push_back(std::make_pair(new CMovementStartAnimation(this, stack), false));
  1538. }
  1539. if(shouldRotate(stack, stack->getPosition(), actionTarget.at(0).hexValue))
  1540. pendingAnims.push_back(std::make_pair(new CReverseAnimation(this, stack, stack->getPosition(), true), false));
  1541. }
  1542. redraw(); // redraw after deactivation, including proper handling of hovered hexes
  1543. if(action->actionType == EActionType::HERO_SPELL) //when hero casts spell
  1544. {
  1545. setHeroAnimation(action->side, 4);
  1546. return;
  1547. }
  1548. if (!stack)
  1549. {
  1550. logGlobal->error("Something wrong with stackNumber in actionStarted. Stack number: %d", action->stackNumber);
  1551. return;
  1552. }
  1553. int txtid = 0;
  1554. switch(action->actionType)
  1555. {
  1556. case EActionType::WAIT:
  1557. txtid = 136;
  1558. break;
  1559. case EActionType::BAD_MORALE:
  1560. txtid = -34; //negative -> no separate singular/plural form
  1561. displayEffect(30, stack->getPosition());
  1562. CCS->soundh->playSound(soundBase::BADMRLE);
  1563. break;
  1564. }
  1565. if(txtid != 0)
  1566. console->addText(stack->formatGeneralMessage(txtid));
  1567. //displaying special abilities
  1568. switch(action->actionType)
  1569. {
  1570. case EActionType::STACK_HEAL:
  1571. displayEffect(74, actionTarget.at(0).hexValue);
  1572. CCS->soundh->playSound(soundBase::REGENER);
  1573. break;
  1574. }
  1575. }
  1576. void CBattleInterface::waitForAnims()
  1577. {
  1578. auto unlockPim = vstd::makeUnlockGuard(*CPlayerInterface::pim);
  1579. animsAreDisplayed.waitWhileTrue();
  1580. }
  1581. void CBattleInterface::bEndTacticPhase()
  1582. {
  1583. setActiveStack(nullptr);
  1584. blockUI(true);
  1585. tacticsMode = false;
  1586. }
  1587. static bool immobile(const CStack *s)
  1588. {
  1589. return !s->Speed(0, true); //should bound stacks be immobile?
  1590. }
  1591. void CBattleInterface::bTacticNextStack(const CStack * current)
  1592. {
  1593. if (!current)
  1594. current = activeStack;
  1595. //no switching stacks when the current one is moving
  1596. waitForAnims();
  1597. TStacks stacksOfMine = tacticianInterface->cb->battleGetStacks(CBattleCallback::ONLY_MINE);
  1598. vstd::erase_if (stacksOfMine, &immobile);
  1599. if (stacksOfMine.empty())
  1600. {
  1601. bEndTacticPhase();
  1602. return;
  1603. }
  1604. auto it = vstd::find(stacksOfMine, current);
  1605. if (it != stacksOfMine.end() && ++it != stacksOfMine.end())
  1606. stackActivated(*it);
  1607. else
  1608. stackActivated(stacksOfMine.front());
  1609. }
  1610. std::string formatDmgRange(std::pair<ui32, ui32> dmgRange)
  1611. {
  1612. if (dmgRange.first != dmgRange.second)
  1613. return (boost::format("%d - %d") % dmgRange.first % dmgRange.second).str();
  1614. else
  1615. return (boost::format("%d") % dmgRange.first).str();
  1616. }
  1617. bool CBattleInterface::canStackMoveHere(const CStack * activeStack, BattleHex myNumber)
  1618. {
  1619. std::vector<BattleHex> acc = curInt->cb->battleGetAvailableHexes(activeStack);
  1620. BattleHex shiftedDest = myNumber.cloneInDirection(activeStack->destShiftDir(), false);
  1621. if (vstd::contains(acc, myNumber))
  1622. return true;
  1623. else if (activeStack->doubleWide() && vstd::contains(acc, shiftedDest))
  1624. return true;
  1625. else
  1626. return false;
  1627. }
  1628. void CBattleInterface::handleHex(BattleHex myNumber, int eventType)
  1629. {
  1630. if (!myTurn || !battleActionsStarted) //we are not permit to do anything
  1631. return;
  1632. // This function handles mouse move over hexes and l-clicking on them.
  1633. // First we decide what happens if player clicks on this hex and set appropriately
  1634. // consoleMsg, cursorFrame/Type and prepare lambda realizeAction.
  1635. //
  1636. // Then, depending whether it was hover/click we either call the action or set tooltip/cursor.
  1637. //used when hovering -> tooltip message and cursor to be set
  1638. std::string consoleMsg;
  1639. bool setCursor = true; //if we want to suppress setting cursor
  1640. ECursor::ECursorTypes cursorType = ECursor::COMBAT;
  1641. int cursorFrame = ECursor::COMBAT_POINTER; //TODO: is this line used?
  1642. //used when l-clicking -> action to be called upon the click
  1643. std::function<void()> realizeAction;
  1644. //Get stack on the hex - first try to grab the alive one, if not found -> allow dead stacks.
  1645. const CStack * shere = curInt->cb->battleGetStackByPos(myNumber, true);
  1646. if(!shere)
  1647. shere = curInt->cb->battleGetStackByPos(myNumber, false);
  1648. if(!activeStack)
  1649. return;
  1650. bool ourStack = false;
  1651. if (shere)
  1652. ourStack = shere->owner == curInt->playerID;
  1653. //stack changed, update selection border
  1654. if (shere != mouseHoveredStack)
  1655. {
  1656. setHoveredStack(shere);
  1657. }
  1658. localActions.clear();
  1659. illegalActions.clear();
  1660. reorderPossibleActionsPriority(activeStack, shere ? MouseHoveredHexContext::OCCUPIED_HEX : MouseHoveredHexContext::UNOCCUPIED_HEX);
  1661. const bool forcedAction = possibleActions.size() == 1;
  1662. for (PossiblePlayerBattleAction action : possibleActions)
  1663. {
  1664. bool legalAction = false; //this action is legal and can be performed
  1665. bool notLegal = false; //this action is not legal and should display message
  1666. switch (action)
  1667. {
  1668. case PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK:
  1669. if (shere && ourStack)
  1670. legalAction = true;
  1671. break;
  1672. case PossiblePlayerBattleAction::MOVE_TACTICS:
  1673. case PossiblePlayerBattleAction::MOVE_STACK:
  1674. {
  1675. if (!(shere && shere->alive())) //we can walk on dead stacks
  1676. {
  1677. if(canStackMoveHere(activeStack, myNumber))
  1678. legalAction = true;
  1679. }
  1680. break;
  1681. }
  1682. case PossiblePlayerBattleAction::ATTACK:
  1683. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  1684. case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
  1685. {
  1686. if(curInt->cb->battleCanAttack(activeStack, shere, myNumber))
  1687. {
  1688. if (isTileAttackable(myNumber)) // move isTileAttackable to be part of battleCanAttack?
  1689. {
  1690. setBattleCursor(myNumber); // temporary - needed for following function :(
  1691. BattleHex attackFromHex = fromWhichHexAttack(myNumber);
  1692. if (attackFromHex >= 0) //we can be in this line when unreachable creature is L - clicked (as of revision 1308)
  1693. legalAction = true;
  1694. }
  1695. }
  1696. }
  1697. break;
  1698. case PossiblePlayerBattleAction::SHOOT:
  1699. if(curInt->cb->battleCanShoot(activeStack, myNumber))
  1700. legalAction = true;
  1701. break;
  1702. case PossiblePlayerBattleAction::ANY_LOCATION:
  1703. if (myNumber > -1) //TODO: this should be checked for all actions
  1704. {
  1705. if(isCastingPossibleHere(activeStack, shere, myNumber))
  1706. legalAction = true;
  1707. }
  1708. break;
  1709. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  1710. if(shere && isCastingPossibleHere(activeStack, shere, myNumber))
  1711. legalAction = true;
  1712. break;
  1713. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
  1714. {
  1715. if(shere && ourStack && shere != activeStack && shere->alive()) //only positive spells for other allied creatures
  1716. {
  1717. int spellID = curInt->cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), shere, CBattleInfoCallback::RANDOM_GENIE);
  1718. if(spellID > -1)
  1719. {
  1720. legalAction = true;
  1721. }
  1722. }
  1723. }
  1724. break;
  1725. case PossiblePlayerBattleAction::OBSTACLE:
  1726. if(isCastingPossibleHere(activeStack, shere, myNumber))
  1727. legalAction = true;
  1728. break;
  1729. case PossiblePlayerBattleAction::TELEPORT:
  1730. {
  1731. //todo: move to mechanics
  1732. ui8 skill = 0;
  1733. if (creatureCasting)
  1734. skill = activeStack->getEffectLevel(SpellID(SpellID::TELEPORT).toSpell());
  1735. else
  1736. skill = getActiveHero()->getEffectLevel(SpellID(SpellID::TELEPORT).toSpell());
  1737. //TODO: explicitely save power, skill
  1738. if (curInt->cb->battleCanTeleportTo(selectedStack, myNumber, skill))
  1739. legalAction = true;
  1740. else
  1741. notLegal = true;
  1742. }
  1743. break;
  1744. case PossiblePlayerBattleAction::SACRIFICE: //choose our living stack to sacrifice
  1745. if (shere && shere != selectedStack && ourStack && shere->alive())
  1746. legalAction = true;
  1747. else
  1748. notLegal = true;
  1749. break;
  1750. case PossiblePlayerBattleAction::FREE_LOCATION:
  1751. legalAction = true;
  1752. if(!isCastingPossibleHere(activeStack, shere, myNumber))
  1753. {
  1754. legalAction = false;
  1755. notLegal = true;
  1756. }
  1757. break;
  1758. case PossiblePlayerBattleAction::CATAPULT:
  1759. if (siegeController && siegeController->isCatapultAttackable(myNumber))
  1760. legalAction = true;
  1761. break;
  1762. case PossiblePlayerBattleAction::HEAL:
  1763. if (shere && ourStack && shere->canBeHealed())
  1764. legalAction = true;
  1765. break;
  1766. case PossiblePlayerBattleAction::RISE_DEMONS:
  1767. if (shere && ourStack && !shere->alive())
  1768. {
  1769. if (!(shere->hasBonusOfType(Bonus::UNDEAD)
  1770. || shere->hasBonusOfType(Bonus::NON_LIVING)
  1771. || shere->hasBonusOfType(Bonus::GARGOYLE)
  1772. || shere->summoned
  1773. || shere->isClone()
  1774. || shere->hasBonusOfType(Bonus::SIEGE_WEAPON)
  1775. ))
  1776. legalAction = true;
  1777. }
  1778. break;
  1779. }
  1780. if (legalAction)
  1781. localActions.push_back (action);
  1782. else if (notLegal || forcedAction)
  1783. illegalActions.push_back (action);
  1784. }
  1785. illegalAction = PossiblePlayerBattleAction::INVALID; //clear it in first place
  1786. if (vstd::contains(localActions, selectedAction)) //try to use last selected action by default
  1787. currentAction = selectedAction;
  1788. else if (localActions.size()) //if not possible, select first available action (they are sorted by suggested priority)
  1789. currentAction = localActions.front();
  1790. else //no legal action possible
  1791. {
  1792. currentAction = PossiblePlayerBattleAction::INVALID; //don't allow to do anything
  1793. if (vstd::contains(illegalActions, selectedAction))
  1794. illegalAction = selectedAction;
  1795. else if (illegalActions.size())
  1796. illegalAction = illegalActions.front();
  1797. else if (shere && ourStack && shere->alive()) //last possibility - display info about our creature
  1798. {
  1799. currentAction = PossiblePlayerBattleAction::CREATURE_INFO;
  1800. }
  1801. else
  1802. illegalAction = PossiblePlayerBattleAction::INVALID; //we should never be here
  1803. }
  1804. bool isCastingPossible = false;
  1805. bool secondaryTarget = false;
  1806. if (currentAction > PossiblePlayerBattleAction::INVALID)
  1807. {
  1808. switch (currentAction) //display console message, realize selected action
  1809. {
  1810. case PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK:
  1811. consoleMsg = (boost::format(CGI->generaltexth->allTexts[481]) % shere->getName()).str(); //Select %s
  1812. realizeAction = [=](){ stackActivated(shere); };
  1813. break;
  1814. case PossiblePlayerBattleAction::MOVE_TACTICS:
  1815. case PossiblePlayerBattleAction::MOVE_STACK:
  1816. if (activeStack->hasBonusOfType(Bonus::FLYING))
  1817. {
  1818. cursorFrame = ECursor::COMBAT_FLY;
  1819. consoleMsg = (boost::format(CGI->generaltexth->allTexts[295]) % activeStack->getName()).str(); //Fly %s here
  1820. }
  1821. else
  1822. {
  1823. cursorFrame = ECursor::COMBAT_MOVE;
  1824. consoleMsg = (boost::format(CGI->generaltexth->allTexts[294]) % activeStack->getName()).str(); //Move %s here
  1825. }
  1826. realizeAction = [=]()
  1827. {
  1828. if(activeStack->doubleWide())
  1829. {
  1830. std::vector<BattleHex> acc = curInt->cb->battleGetAvailableHexes(activeStack);
  1831. BattleHex shiftedDest = myNumber.cloneInDirection(activeStack->destShiftDir(), false);
  1832. if(vstd::contains(acc, myNumber))
  1833. giveCommand(EActionType::WALK, myNumber);
  1834. else if(vstd::contains(acc, shiftedDest))
  1835. giveCommand(EActionType::WALK, shiftedDest);
  1836. }
  1837. else
  1838. {
  1839. giveCommand(EActionType::WALK, myNumber);
  1840. }
  1841. };
  1842. break;
  1843. case PossiblePlayerBattleAction::ATTACK:
  1844. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  1845. case PossiblePlayerBattleAction::ATTACK_AND_RETURN: //TODO: allow to disable return
  1846. {
  1847. setBattleCursor(myNumber); //handle direction of cursor and attackable tile
  1848. setCursor = false; //don't overwrite settings from the call above //TODO: what does it mean?
  1849. bool returnAfterAttack = currentAction == PossiblePlayerBattleAction::ATTACK_AND_RETURN;
  1850. realizeAction = [=]()
  1851. {
  1852. BattleHex attackFromHex = fromWhichHexAttack(myNumber);
  1853. if(attackFromHex.isValid()) //we can be in this line when unreachable creature is L - clicked (as of revision 1308)
  1854. {
  1855. auto command = new BattleAction(BattleAction::makeMeleeAttack(activeStack, myNumber, attackFromHex, returnAfterAttack));
  1856. sendCommand(command, activeStack);
  1857. }
  1858. };
  1859. TDmgRange damage = curInt->cb->battleEstimateDamage(activeStack, shere);
  1860. std::string estDmgText = formatDmgRange(std::make_pair((ui32)damage.first, (ui32)damage.second)); //calculating estimated dmg
  1861. consoleMsg = (boost::format(CGI->generaltexth->allTexts[36]) % shere->getName() % estDmgText).str(); //Attack %s (%s damage)
  1862. }
  1863. break;
  1864. case PossiblePlayerBattleAction::SHOOT:
  1865. {
  1866. if (curInt->cb->battleHasShootingPenalty(activeStack, myNumber))
  1867. cursorFrame = ECursor::COMBAT_SHOOT_PENALTY;
  1868. else
  1869. cursorFrame = ECursor::COMBAT_SHOOT;
  1870. realizeAction = [=](){giveCommand(EActionType::SHOOT, myNumber);};
  1871. TDmgRange damage = curInt->cb->battleEstimateDamage(activeStack, shere);
  1872. std::string estDmgText = formatDmgRange(std::make_pair((ui32)damage.first, (ui32)damage.second)); //calculating estimated dmg
  1873. //printing - Shoot %s (%d shots left, %s damage)
  1874. consoleMsg = (boost::format(CGI->generaltexth->allTexts[296]) % shere->getName() % activeStack->shots.available() % estDmgText).str();
  1875. }
  1876. break;
  1877. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  1878. sp = CGI->spellh->objects[creatureCasting ? creatureSpellToCast : spellToCast->actionSubtype]; //necessary if creature has random Genie spell at same time
  1879. consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[27]) % sp->name % shere->getName()); //Cast %s on %s
  1880. switch (sp->id)
  1881. {
  1882. case SpellID::SACRIFICE:
  1883. case SpellID::TELEPORT:
  1884. selectedStack = shere; //remember first target
  1885. secondaryTarget = true;
  1886. break;
  1887. }
  1888. isCastingPossible = true;
  1889. break;
  1890. case PossiblePlayerBattleAction::ANY_LOCATION:
  1891. sp = CGI->spellh->objects[creatureCasting ? creatureSpellToCast : spellToCast->actionSubtype]; //necessary if creature has random Genie spell at same time
  1892. consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[26]) % sp->name); //Cast %s
  1893. isCastingPossible = true;
  1894. break;
  1895. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL: //we assume that teleport / sacrifice will never be available as random spell
  1896. sp = nullptr;
  1897. consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[301]) % shere->getName()); //Cast a spell on %
  1898. creatureCasting = true;
  1899. isCastingPossible = true;
  1900. break;
  1901. case PossiblePlayerBattleAction::TELEPORT:
  1902. consoleMsg = CGI->generaltexth->allTexts[25]; //Teleport Here
  1903. cursorFrame = ECursor::COMBAT_TELEPORT;
  1904. isCastingPossible = true;
  1905. break;
  1906. case PossiblePlayerBattleAction::OBSTACLE:
  1907. consoleMsg = CGI->generaltexth->allTexts[550];
  1908. //TODO: remove obstacle cursor
  1909. isCastingPossible = true;
  1910. break;
  1911. case PossiblePlayerBattleAction::SACRIFICE:
  1912. consoleMsg = (boost::format(CGI->generaltexth->allTexts[549]) % shere->getName()).str(); //sacrifice the %s
  1913. cursorFrame = ECursor::COMBAT_SACRIFICE;
  1914. isCastingPossible = true;
  1915. break;
  1916. case PossiblePlayerBattleAction::FREE_LOCATION:
  1917. consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[26]) % sp->name); //Cast %s
  1918. isCastingPossible = true;
  1919. break;
  1920. case PossiblePlayerBattleAction::HEAL:
  1921. cursorFrame = ECursor::COMBAT_HEAL;
  1922. consoleMsg = (boost::format(CGI->generaltexth->allTexts[419]) % shere->getName()).str(); //Apply first aid to the %s
  1923. realizeAction = [=](){ giveCommand(EActionType::STACK_HEAL, myNumber); }; //command healing
  1924. break;
  1925. case PossiblePlayerBattleAction::RISE_DEMONS:
  1926. cursorType = ECursor::SPELLBOOK;
  1927. realizeAction = [=]()
  1928. {
  1929. giveCommand(EActionType::DAEMON_SUMMONING, myNumber);
  1930. };
  1931. break;
  1932. case PossiblePlayerBattleAction::CATAPULT:
  1933. cursorFrame = ECursor::COMBAT_SHOOT_CATAPULT;
  1934. realizeAction = [=](){ giveCommand(EActionType::CATAPULT, myNumber); };
  1935. break;
  1936. case PossiblePlayerBattleAction::CREATURE_INFO:
  1937. {
  1938. cursorFrame = ECursor::COMBAT_QUERY;
  1939. consoleMsg = (boost::format(CGI->generaltexth->allTexts[297]) % shere->getName()).str();
  1940. realizeAction = [=](){ GH.pushIntT<CStackWindow>(shere, false); };
  1941. break;
  1942. }
  1943. }
  1944. }
  1945. else //no possible valid action, display message
  1946. {
  1947. switch (illegalAction)
  1948. {
  1949. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  1950. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
  1951. cursorFrame = ECursor::COMBAT_BLOCKED;
  1952. consoleMsg = CGI->generaltexth->allTexts[23];
  1953. break;
  1954. case PossiblePlayerBattleAction::TELEPORT:
  1955. cursorFrame = ECursor::COMBAT_BLOCKED;
  1956. consoleMsg = CGI->generaltexth->allTexts[24]; //Invalid Teleport Destination
  1957. break;
  1958. case PossiblePlayerBattleAction::SACRIFICE:
  1959. consoleMsg = CGI->generaltexth->allTexts[543]; //choose army to sacrifice
  1960. break;
  1961. case PossiblePlayerBattleAction::FREE_LOCATION:
  1962. cursorFrame = ECursor::COMBAT_BLOCKED;
  1963. consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[181]) % sp->name); //No room to place %s here
  1964. break;
  1965. default:
  1966. if (myNumber == -1)
  1967. CCS->curh->changeGraphic(ECursor::COMBAT, ECursor::COMBAT_POINTER); //set neutral cursor over menu etc.
  1968. else
  1969. cursorFrame = ECursor::COMBAT_BLOCKED;
  1970. break;
  1971. }
  1972. }
  1973. if (isCastingPossible) //common part
  1974. {
  1975. switch (currentAction) //don't use that with teleport / sacrifice
  1976. {
  1977. case PossiblePlayerBattleAction::TELEPORT: //FIXME: more generic solution?
  1978. case PossiblePlayerBattleAction::SACRIFICE:
  1979. break;
  1980. default:
  1981. cursorType = ECursor::SPELLBOOK;
  1982. cursorFrame = 0;
  1983. if (consoleMsg.empty() && sp)
  1984. consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[26]) % sp->name); //Cast %s
  1985. break;
  1986. }
  1987. realizeAction = [=]()
  1988. {
  1989. if(secondaryTarget) //select that target now
  1990. {
  1991. possibleActions.clear();
  1992. switch (sp->id.toEnum())
  1993. {
  1994. case SpellID::TELEPORT: //don't cast spell yet, only select target
  1995. spellToCast->aimToUnit(shere);
  1996. possibleActions.push_back(PossiblePlayerBattleAction::TELEPORT);
  1997. break;
  1998. case SpellID::SACRIFICE:
  1999. spellToCast->aimToHex(myNumber);
  2000. possibleActions.push_back(PossiblePlayerBattleAction::SACRIFICE);
  2001. break;
  2002. }
  2003. }
  2004. else
  2005. {
  2006. if (creatureCasting)
  2007. {
  2008. if (sp)
  2009. {
  2010. giveCommand(EActionType::MONSTER_SPELL, myNumber, creatureSpellToCast);
  2011. }
  2012. else //unknown random spell
  2013. {
  2014. giveCommand(EActionType::MONSTER_SPELL, myNumber);
  2015. }
  2016. }
  2017. else
  2018. {
  2019. assert(sp);
  2020. switch (sp->id.toEnum())
  2021. {
  2022. case SpellID::SACRIFICE:
  2023. spellToCast->aimToUnit(shere);//victim
  2024. break;
  2025. default:
  2026. spellToCast->aimToHex(myNumber);
  2027. break;
  2028. }
  2029. curInt->cb->battleMakeAction(spellToCast.get());
  2030. endCastingSpell();
  2031. }
  2032. selectedStack = nullptr;
  2033. }
  2034. };
  2035. }
  2036. {
  2037. if (eventType == MOVE)
  2038. {
  2039. if (setCursor)
  2040. CCS->curh->changeGraphic(cursorType, cursorFrame);
  2041. this->console->alterText(consoleMsg);
  2042. this->console->whoSetAlter = 0;
  2043. }
  2044. if (eventType == LCLICK && realizeAction)
  2045. {
  2046. //opening creature window shouldn't affect myTurn...
  2047. if ((currentAction != PossiblePlayerBattleAction::CREATURE_INFO) && !secondaryTarget)
  2048. {
  2049. myTurn = false; //tends to crash with empty calls
  2050. }
  2051. realizeAction();
  2052. if (!secondaryTarget) //do not replace teleport or sacrifice cursor
  2053. CCS->curh->changeGraphic(ECursor::COMBAT, ECursor::COMBAT_POINTER);
  2054. this->console->alterText("");
  2055. }
  2056. }
  2057. }
  2058. bool CBattleInterface::isCastingPossibleHere(const CStack *sactive, const CStack *shere, BattleHex myNumber)
  2059. {
  2060. creatureCasting = stackCanCastSpell && !spellDestSelectMode; //TODO: allow creatures to cast aimed spells
  2061. bool isCastingPossible = true;
  2062. int spellID = -1;
  2063. if (creatureCasting)
  2064. {
  2065. if (creatureSpellToCast > -1 && (shere != sactive)) //can't cast on itself
  2066. spellID = creatureSpellToCast; //TODO: merge with SpellTocast?
  2067. }
  2068. else //hero casting
  2069. {
  2070. spellID = spellToCast->actionSubtype;
  2071. }
  2072. sp = nullptr;
  2073. if (spellID >= 0)
  2074. sp = CGI->spellh->objects[spellID];
  2075. if (sp)
  2076. {
  2077. const spells::Caster *caster = creatureCasting ? static_cast<const spells::Caster *>(sactive) : static_cast<const spells::Caster *>(curInt->cb->battleGetMyHero());
  2078. if (caster == nullptr)
  2079. {
  2080. isCastingPossible = false;//just in case
  2081. }
  2082. else
  2083. {
  2084. const spells::Mode mode = creatureCasting ? spells::Mode::CREATURE_ACTIVE : spells::Mode::HERO;
  2085. spells::Target target;
  2086. target.emplace_back(myNumber);
  2087. spells::BattleCast cast(curInt->cb.get(), caster, mode, sp);
  2088. auto m = sp->battleMechanics(&cast);
  2089. spells::detail::ProblemImpl problem; //todo: display problem in status bar
  2090. isCastingPossible = m->canBeCastAt(target, problem);
  2091. }
  2092. }
  2093. else
  2094. isCastingPossible = false;
  2095. if (!myNumber.isAvailable() && !shere) //empty tile outside battlefield (or in the unavailable border column)
  2096. isCastingPossible = false;
  2097. return isCastingPossible;
  2098. }
  2099. BattleHex CBattleInterface::fromWhichHexAttack(BattleHex myNumber)
  2100. {
  2101. //TODO far too much repeating code
  2102. BattleHex destHex;
  2103. switch(CCS->curh->frame)
  2104. {
  2105. case 12: //from bottom right
  2106. {
  2107. bool doubleWide = activeStack->doubleWide();
  2108. destHex = myNumber + ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH : GameConstants::BFIELD_WIDTH+1 ) +
  2109. (activeStack->side == BattleSide::ATTACKER && doubleWide ? 1 : 0);
  2110. if(vstd::contains(occupyableHexes, destHex))
  2111. return destHex;
  2112. else if(activeStack->side == BattleSide::ATTACKER)
  2113. {
  2114. if (vstd::contains(occupyableHexes, destHex+1))
  2115. return destHex+1;
  2116. }
  2117. else //if we are defender
  2118. {
  2119. if(vstd::contains(occupyableHexes, destHex-1))
  2120. return destHex-1;
  2121. }
  2122. break;
  2123. }
  2124. case 7: //from bottom left
  2125. {
  2126. destHex = myNumber + ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH-1 : GameConstants::BFIELD_WIDTH );
  2127. if (vstd::contains(occupyableHexes, destHex))
  2128. return destHex;
  2129. else if(activeStack->side == BattleSide::ATTACKER)
  2130. {
  2131. if(vstd::contains(occupyableHexes, destHex+1))
  2132. return destHex+1;
  2133. }
  2134. else //we are defender
  2135. {
  2136. if(vstd::contains(occupyableHexes, destHex-1))
  2137. return destHex-1;
  2138. }
  2139. break;
  2140. }
  2141. case 8: //from left
  2142. {
  2143. if(activeStack->doubleWide() && activeStack->side == BattleSide::DEFENDER)
  2144. {
  2145. std::vector<BattleHex> acc = curInt->cb->battleGetAvailableHexes(activeStack);
  2146. if (vstd::contains(acc, myNumber))
  2147. return myNumber - 1;
  2148. else
  2149. return myNumber - 2;
  2150. }
  2151. else
  2152. {
  2153. return myNumber - 1;
  2154. }
  2155. break;
  2156. }
  2157. case 9: //from top left
  2158. {
  2159. destHex = myNumber - ((myNumber/GameConstants::BFIELD_WIDTH) % 2 ? GameConstants::BFIELD_WIDTH + 1 : GameConstants::BFIELD_WIDTH);
  2160. if(vstd::contains(occupyableHexes, destHex))
  2161. return destHex;
  2162. else if(activeStack->side == BattleSide::ATTACKER)
  2163. {
  2164. if(vstd::contains(occupyableHexes, destHex+1))
  2165. return destHex+1;
  2166. }
  2167. else //if we are defender
  2168. {
  2169. if(vstd::contains(occupyableHexes, destHex-1))
  2170. return destHex-1;
  2171. }
  2172. break;
  2173. }
  2174. case 10: //from top right
  2175. {
  2176. bool doubleWide = activeStack->doubleWide();
  2177. destHex = myNumber - ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH : GameConstants::BFIELD_WIDTH-1 ) +
  2178. (activeStack->side == BattleSide::ATTACKER && doubleWide ? 1 : 0);
  2179. if(vstd::contains(occupyableHexes, destHex))
  2180. return destHex;
  2181. else if(activeStack->side == BattleSide::ATTACKER)
  2182. {
  2183. if(vstd::contains(occupyableHexes, destHex+1))
  2184. return destHex+1;
  2185. }
  2186. else //if we are defender
  2187. {
  2188. if(vstd::contains(occupyableHexes, destHex-1))
  2189. return destHex-1;
  2190. }
  2191. break;
  2192. }
  2193. case 11: //from right
  2194. {
  2195. if(activeStack->doubleWide() && activeStack->side == BattleSide::ATTACKER)
  2196. {
  2197. std::vector<BattleHex> acc = curInt->cb->battleGetAvailableHexes(activeStack);
  2198. if(vstd::contains(acc, myNumber))
  2199. return myNumber + 1;
  2200. else
  2201. return myNumber + 2;
  2202. }
  2203. else
  2204. {
  2205. return myNumber + 1;
  2206. }
  2207. break;
  2208. }
  2209. case 13: //from bottom
  2210. {
  2211. destHex = myNumber + ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH : GameConstants::BFIELD_WIDTH+1 );
  2212. if(vstd::contains(occupyableHexes, destHex))
  2213. return destHex;
  2214. else if(activeStack->side == BattleSide::ATTACKER)
  2215. {
  2216. if(vstd::contains(occupyableHexes, destHex+1))
  2217. return destHex+1;
  2218. }
  2219. else //if we are defender
  2220. {
  2221. if(vstd::contains(occupyableHexes, destHex-1))
  2222. return destHex-1;
  2223. }
  2224. break;
  2225. }
  2226. case 14: //from top
  2227. {
  2228. destHex = myNumber - ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH : GameConstants::BFIELD_WIDTH-1 );
  2229. if (vstd::contains(occupyableHexes, destHex))
  2230. return destHex;
  2231. else if(activeStack->side == BattleSide::ATTACKER)
  2232. {
  2233. if(vstd::contains(occupyableHexes, destHex+1))
  2234. return destHex+1;
  2235. }
  2236. else //if we are defender
  2237. {
  2238. if(vstd::contains(occupyableHexes, destHex-1))
  2239. return destHex-1;
  2240. }
  2241. break;
  2242. }
  2243. }
  2244. return -1;
  2245. }
  2246. Rect CBattleInterface::hexPosition(BattleHex hex) const
  2247. {
  2248. int x = 14 + ((hex.getY())%2==0 ? 22 : 0) + 44*hex.getX() + pos.x;
  2249. int y = 86 + 42 *hex.getY() + pos.y;
  2250. int w = cellShade->w;
  2251. int h = cellShade->h;
  2252. return Rect(x, y, w, h);
  2253. }
  2254. void CBattleInterface::obstaclePlaced(const CObstacleInstance & oi)
  2255. {
  2256. obstacleController->obstaclePlaced(oi);
  2257. }
  2258. const CGHeroInstance *CBattleInterface::currentHero() const
  2259. {
  2260. if (attackingHeroInstance->tempOwner == curInt->playerID)
  2261. return attackingHeroInstance;
  2262. else
  2263. return defendingHeroInstance;
  2264. }
  2265. InfoAboutHero CBattleInterface::enemyHero() const
  2266. {
  2267. InfoAboutHero ret;
  2268. if (attackingHeroInstance->tempOwner == curInt->playerID)
  2269. curInt->cb->getHeroInfo(defendingHeroInstance, ret);
  2270. else
  2271. curInt->cb->getHeroInfo(attackingHeroInstance, ret);
  2272. return ret;
  2273. }
  2274. void CBattleInterface::requestAutofightingAIToTakeAction()
  2275. {
  2276. assert(curInt->isAutoFightOn);
  2277. boost::thread aiThread([&]()
  2278. {
  2279. auto ba = make_unique<BattleAction>(curInt->autofightingAI->activeStack(activeStack));
  2280. if(curInt->cb->battleIsFinished())
  2281. {
  2282. return; // battle finished with spellcast
  2283. }
  2284. if (curInt->isAutoFightOn)
  2285. {
  2286. if (tacticsMode)
  2287. {
  2288. // Always end tactics mode. Player interface is blocked currently, so it's not possible that
  2289. // the AI can take any action except end tactics phase (AI actions won't be triggered)
  2290. //TODO implement the possibility that the AI will be triggered for further actions
  2291. //TODO any solution to merge tactics phase & normal phase in the way it is handled by the player and battle interface?
  2292. setActiveStack(nullptr);
  2293. blockUI(true);
  2294. tacticsMode = false;
  2295. }
  2296. else
  2297. {
  2298. givenCommand.setn(ba.release());
  2299. }
  2300. }
  2301. else
  2302. {
  2303. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  2304. activateStack();
  2305. }
  2306. });
  2307. aiThread.detach();
  2308. }
  2309. void CBattleInterface::showAll(SDL_Surface *to)
  2310. {
  2311. show(to);
  2312. }
  2313. void CBattleInterface::show(SDL_Surface *to)
  2314. {
  2315. assert(to);
  2316. SDL_Rect buf;
  2317. SDL_GetClipRect(to, &buf);
  2318. SDL_SetClipRect(to, &pos);
  2319. ++animCount;
  2320. showBackground(to);
  2321. showBattlefieldObjects(to);
  2322. projectilesController->showProjectiles(to);
  2323. if(battleActionsStarted)
  2324. updateBattleAnimations();
  2325. SDL_SetClipRect(to, &buf); //restoring previous clip_rect
  2326. showInterface(to);
  2327. //activation of next stack
  2328. if (pendingAnims.empty() && stackToActivate != nullptr && battleActionsStarted) //FIXME: watch for recursive infinite loop here when working with this file, this needs rework anyway...
  2329. {
  2330. activateStack();
  2331. //we may have changed active interface (another side in hot-seat),
  2332. // so we can't continue drawing with old setting.
  2333. show(to);
  2334. }
  2335. }
  2336. void CBattleInterface::showBackground(SDL_Surface *to)
  2337. {
  2338. if (activeStack != nullptr && creAnims[activeStack->ID]->isIdle()) //show everything with range
  2339. {
  2340. // FIXME: any *real* reason to keep this separate? Speed difference can't be that big
  2341. blitAt(backgroundWithHexes, pos.x, pos.y, to);
  2342. }
  2343. else
  2344. {
  2345. showBackgroundImage(to);
  2346. obstacleController->showAbsoluteObstacles(to);
  2347. if ( siegeController )
  2348. siegeController->showAbsoluteObstacles(to);
  2349. }
  2350. showHighlightedHexes(to);
  2351. }
  2352. void CBattleInterface::showBackgroundImage(SDL_Surface *to)
  2353. {
  2354. blitAt(background, pos.x, pos.y, to);
  2355. if (settings["battle"]["cellBorders"].Bool())
  2356. {
  2357. CSDL_Ext::blit8bppAlphaTo24bpp(cellBorders, nullptr, to, &pos);
  2358. }
  2359. }
  2360. void CBattleInterface::showHighlightedHexes(SDL_Surface *to)
  2361. {
  2362. bool delayedBlit = false; //workaround for blitting enemy stack hex without mouse shadow with stack range on
  2363. if(activeStack && settings["battle"]["stackRange"].Bool())
  2364. {
  2365. std::set<BattleHex> set = curInt->cb->battleGetAttackedHexes(activeStack, currentlyHoveredHex, attackingHex);
  2366. for(BattleHex hex : set)
  2367. if(hex != currentlyHoveredHex)
  2368. showHighlightedHex(to, hex);
  2369. // display the movement shadow of the stack at b (i.e. stack under mouse)
  2370. const CStack * const shere = curInt->cb->battleGetStackByPos(currentlyHoveredHex, false);
  2371. if(shere && shere != activeStack && shere->alive())
  2372. {
  2373. std::vector<BattleHex> v = curInt->cb->battleGetAvailableHexes(shere, true, nullptr);
  2374. for(BattleHex hex : v)
  2375. {
  2376. if(hex != currentlyHoveredHex)
  2377. showHighlightedHex(to, hex);
  2378. else if(!settings["battle"]["mouseShadow"].Bool())
  2379. delayedBlit = true; //blit at the end of method to avoid graphic artifacts
  2380. else
  2381. showHighlightedHex(to, hex, true); //blit now and blit 2nd time later for darker shadow - avoids graphic artifacts
  2382. }
  2383. }
  2384. }
  2385. for(int b=0; b<GameConstants::BFIELD_SIZE; ++b)
  2386. {
  2387. if(bfield[b]->strictHovered && bfield[b]->hovered)
  2388. {
  2389. if(previouslyHoveredHex == -1)
  2390. previouslyHoveredHex = b; //something to start with
  2391. if(currentlyHoveredHex == -1)
  2392. currentlyHoveredHex = b; //something to start with
  2393. if(currentlyHoveredHex != b) //repair hover info
  2394. {
  2395. previouslyHoveredHex = currentlyHoveredHex;
  2396. currentlyHoveredHex = b;
  2397. }
  2398. if(settings["battle"]["mouseShadow"].Bool() || delayedBlit)
  2399. {
  2400. const spells::Caster *caster = nullptr;
  2401. const CSpell *spell = nullptr;
  2402. spells::Mode mode = spells::Mode::HERO;
  2403. if(spellToCast)//hero casts spell
  2404. {
  2405. spell = SpellID(spellToCast->actionSubtype).toSpell();
  2406. caster = getActiveHero();
  2407. }
  2408. else if(creatureSpellToCast >= 0 && stackCanCastSpell && creatureCasting)//stack casts spell
  2409. {
  2410. spell = SpellID(creatureSpellToCast).toSpell();
  2411. caster = activeStack;
  2412. mode = spells::Mode::CREATURE_ACTIVE;
  2413. }
  2414. if(caster && spell) //when casting spell
  2415. {
  2416. // printing shaded hex(es)
  2417. spells::BattleCast event(curInt->cb.get(), caster, mode, spell);
  2418. auto shaded = spell->battleMechanics(&event)->rangeInHexes(currentlyHoveredHex);
  2419. for(BattleHex shadedHex : shaded)
  2420. {
  2421. if((shadedHex.getX() != 0) && (shadedHex.getX() != GameConstants::BFIELD_WIDTH - 1))
  2422. showHighlightedHex(to, shadedHex, true);
  2423. }
  2424. }
  2425. else if(active || delayedBlit) //always highlight pointed hex, keep this condition last in this method for correct behavior
  2426. {
  2427. if(currentlyHoveredHex.getX() != 0
  2428. && currentlyHoveredHex.getX() != GameConstants::BFIELD_WIDTH - 1)
  2429. showHighlightedHex(to, currentlyHoveredHex, true); //keep true for OH3 behavior: hovered hex frame "thinner"
  2430. }
  2431. }
  2432. }
  2433. }
  2434. }
  2435. void CBattleInterface::showHighlightedHex(SDL_Surface *to, BattleHex hex, bool darkBorder)
  2436. {
  2437. int x = 14 + (hex.getY() % 2 == 0 ? 22 : 0) + 44 *(hex.getX()) + pos.x;
  2438. int y = 86 + 42 *hex.getY() + pos.y;
  2439. SDL_Rect temp_rect = genRect (cellShade->h, cellShade->w, x, y);
  2440. CSDL_Ext::blit8bppAlphaTo24bpp (cellShade, nullptr, to, &temp_rect);
  2441. if(!darkBorder && settings["battle"]["cellBorders"].Bool())
  2442. CSDL_Ext::blit8bppAlphaTo24bpp(cellBorder, nullptr, to, &temp_rect); //redraw border to make it light green instead of shaded
  2443. }
  2444. void CBattleInterface::showBattlefieldObjects(SDL_Surface *to)
  2445. {
  2446. auto showHexEntry = [&](BattleObjectsByHex::HexData & hex)
  2447. {
  2448. if (siegeController)
  2449. siegeController->showPiecesOfWall(to, hex.walls);
  2450. obstacleController->showObstacles(to, hex.obstacles);
  2451. showAliveStacks(to, hex.alive);
  2452. showBattleEffects(to, hex.effects);
  2453. };
  2454. BattleObjectsByHex objects = sortObjectsByHex();
  2455. // dead stacks should be blit first
  2456. showStacks(to, objects.beforeAll.dead);
  2457. for (auto & data : objects.hex)
  2458. showStacks(to, data.dead);
  2459. showStacks(to, objects.afterAll.dead);
  2460. // display objects that must be blit before anything else (e.g. topmost walls)
  2461. showHexEntry(objects.beforeAll);
  2462. // show heroes after "beforeAll" - e.g. topmost wall in siege
  2463. if (attackingHero)
  2464. attackingHero->show(to);
  2465. if (defendingHero)
  2466. defendingHero->show(to);
  2467. // actual blit of most of objects, hex by hex
  2468. // NOTE: row-by-row blitting may be a better approach
  2469. for (auto &data : objects.hex)
  2470. showHexEntry(data);
  2471. // objects that must be blit *after* everything else - e.g. bottom tower or some spell effects
  2472. showHexEntry(objects.afterAll);
  2473. }
  2474. void CBattleInterface::showAliveStacks(SDL_Surface *to, std::vector<const CStack *> stacks)
  2475. {
  2476. BattleHex currentActionTarget;
  2477. if(curInt->curAction)
  2478. {
  2479. auto target = curInt->curAction->getTarget(curInt->cb.get());
  2480. if(!target.empty())
  2481. currentActionTarget = target.at(0).hexValue;
  2482. }
  2483. auto isAmountBoxVisible = [&](const CStack *stack) -> bool
  2484. {
  2485. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON) && stack->getCount() == 1) //do not show box for singular war machines, stacked war machines with box shown are supported as extension feature
  2486. return false;
  2487. if(stack->getCount() == 0) //hide box when target is going to die anyway - do not display "0 creatures"
  2488. return false;
  2489. for(auto anim : pendingAnims) //no matter what other conditions below are, hide box when creature is playing hit animation
  2490. {
  2491. auto hitAnimation = dynamic_cast<CDefenceAnimation*>(anim.first);
  2492. if(hitAnimation && (hitAnimation->stack->ID == stack->ID)) //we process only "current creature" as other creatures will be processed reliably on their own iteration
  2493. return false;
  2494. }
  2495. if(curInt->curAction)
  2496. {
  2497. if(curInt->curAction->stackNumber == stack->ID) //stack is currently taking action (is not a target of another creature's action etc)
  2498. {
  2499. if(curInt->curAction->actionType == EActionType::WALK || curInt->curAction->actionType == EActionType::SHOOT) //hide when stack walks or shoots
  2500. return false;
  2501. else if(curInt->curAction->actionType == EActionType::WALK_AND_ATTACK && currentActionTarget != stack->getPosition()) //when attacking, hide until walk phase finished
  2502. return false;
  2503. }
  2504. if(curInt->curAction->actionType == EActionType::SHOOT && currentActionTarget == stack->getPosition()) //hide if we are ranged attack target
  2505. return false;
  2506. }
  2507. return true;
  2508. };
  2509. auto getEffectsPositivness = [&](const std::vector<si32> & activeSpells) -> int
  2510. {
  2511. int pos = 0;
  2512. for (const auto & spellId : activeSpells)
  2513. {
  2514. pos += CGI->spellh->objects.at(spellId)->positiveness;
  2515. }
  2516. return pos;
  2517. };
  2518. auto getAmountBoxBackground = [&](int positivness) -> SDL_Surface *
  2519. {
  2520. if (positivness > 0)
  2521. return amountPositive;
  2522. if (positivness < 0)
  2523. return amountNegative;
  2524. return amountEffNeutral;
  2525. };
  2526. showStacks(to, stacks); // Actual display of all stacks
  2527. for (auto & stack : stacks)
  2528. {
  2529. assert(stack);
  2530. //printing amount
  2531. if (isAmountBoxVisible(stack))
  2532. {
  2533. const int sideShift = stack->side == BattleSide::ATTACKER ? 1 : -1;
  2534. const int reverseSideShift = stack->side == BattleSide::ATTACKER ? -1 : 1;
  2535. const BattleHex nextPos = stack->getPosition() + sideShift;
  2536. const bool edge = stack->getPosition() % GameConstants::BFIELD_WIDTH == (stack->side == BattleSide::ATTACKER ? GameConstants::BFIELD_WIDTH - 2 : 1);
  2537. const bool moveInside = !edge && !stackCountOutsideHexes[nextPos];
  2538. int xAdd = (stack->side == BattleSide::ATTACKER ? 220 : 202) +
  2539. (stack->doubleWide() ? 44 : 0) * sideShift +
  2540. (moveInside ? amountNormal->w + 10 : 0) * reverseSideShift;
  2541. int yAdd = 260 + ((stack->side == BattleSide::ATTACKER || moveInside) ? 0 : -15);
  2542. //blitting amount background box
  2543. SDL_Surface *amountBG = amountNormal;
  2544. std::vector<si32> activeSpells = stack->activeSpells();
  2545. if (!activeSpells.empty())
  2546. amountBG = getAmountBoxBackground(getEffectsPositivness(activeSpells));
  2547. SDL_Rect temp_rect = genRect(amountBG->h, amountBG->w, creAnims[stack->ID]->pos.x + xAdd, creAnims[stack->ID]->pos.y + yAdd);
  2548. SDL_BlitSurface(amountBG, nullptr, to, &temp_rect);
  2549. //blitting amount
  2550. Point textPos(creAnims[stack->ID]->pos.x + xAdd + amountNormal->w/2,
  2551. creAnims[stack->ID]->pos.y + yAdd + amountNormal->h/2);
  2552. graphics->fonts[FONT_TINY]->renderTextCenter(to, makeNumberShort(stack->getCount()), Colors::WHITE, textPos);
  2553. }
  2554. }
  2555. }
  2556. void CBattleInterface::showStacks(SDL_Surface *to, std::vector<const CStack *> stacks)
  2557. {
  2558. for (const CStack *stack : stacks)
  2559. {
  2560. creAnims[stack->ID]->nextFrame(to, creDir[stack->ID]); // do actual blit
  2561. creAnims[stack->ID]->incrementFrame(float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000);
  2562. }
  2563. }
  2564. void CBattleInterface::showBattleEffects(SDL_Surface *to, const std::vector<const BattleEffect *> &battleEffects)
  2565. {
  2566. for (auto & elem : battleEffects)
  2567. {
  2568. int currentFrame = static_cast<int>(floor(elem->currentFrame));
  2569. currentFrame %= elem->animation->size();
  2570. auto img = elem->animation->getImage(currentFrame);
  2571. SDL_Rect temp_rect = genRect(img->height(), img->width(), elem->x, elem->y);
  2572. img->draw(to, &temp_rect, nullptr);
  2573. }
  2574. }
  2575. void CBattleInterface::showInterface(SDL_Surface *to)
  2576. {
  2577. blitAt(menu, pos.x, 556 + pos.y, to);
  2578. if (tacticsMode)
  2579. {
  2580. btactNext->showAll(to);
  2581. btactEnd->showAll(to);
  2582. }
  2583. else
  2584. {
  2585. console->showAll(to);
  2586. bConsoleUp->showAll(to);
  2587. bConsoleDown->showAll(to);
  2588. }
  2589. //showing buttons
  2590. bOptions->showAll(to);
  2591. bSurrender->showAll(to);
  2592. bFlee->showAll(to);
  2593. bAutofight->showAll(to);
  2594. bSpell->showAll(to);
  2595. bWait->showAll(to);
  2596. bDefence->showAll(to);
  2597. //showing in-game console
  2598. LOCPLINT->cingconsole->show(to);
  2599. Rect posWithQueue = Rect(pos.x, pos.y, 800, 600);
  2600. if (settings["battle"]["showQueue"].Bool())
  2601. {
  2602. if (!queue->embedded)
  2603. {
  2604. posWithQueue.y -= queue->pos.h;
  2605. posWithQueue.h += queue->pos.h;
  2606. }
  2607. queue->showAll(to);
  2608. }
  2609. //printing border around interface
  2610. if (screen->w != 800 || screen->h !=600)
  2611. {
  2612. CMessage::drawBorder(curInt->playerID,to,posWithQueue.w + 28, posWithQueue.h + 28, posWithQueue.x-14, posWithQueue.y-15);
  2613. }
  2614. }
  2615. BattleObjectsByHex CBattleInterface::sortObjectsByHex()
  2616. {
  2617. auto getCurrentPosition = [&](const CStack *stack) -> BattleHex
  2618. {
  2619. for (auto & anim : pendingAnims)
  2620. {
  2621. // certainly ugly workaround but fixes quite annoying bug
  2622. // stack position will be updated only *after* movement is finished
  2623. // before this - stack is always at its initial position. Thus we need to find
  2624. // its current position. Which can be found only in this class
  2625. if (CMovementAnimation *move = dynamic_cast<CMovementAnimation*>(anim.first))
  2626. {
  2627. if (move->stack == stack)
  2628. return move->nextHex;
  2629. }
  2630. }
  2631. return stack->getPosition();
  2632. };
  2633. BattleObjectsByHex sorted;
  2634. auto stacks = curInt->cb->battleGetStacksIf([](const CStack *s)
  2635. {
  2636. return !s->isTurret();
  2637. });
  2638. // Sort creatures
  2639. for (auto & stack : stacks)
  2640. {
  2641. if (creAnims.find(stack->ID) == creAnims.end()) //e.g. for summoned but not yet handled stacks
  2642. continue;
  2643. if (stack->initialPosition < 0) // turret shooters are handled separately
  2644. continue;
  2645. //FIXME: hack to ignore ghost stacks
  2646. if ((creAnims[stack->ID]->getType() == CCreatureAnim::DEAD || creAnims[stack->ID]->getType() == CCreatureAnim::HOLDING) && stack->isGhost())
  2647. ;//ignore
  2648. else if (!creAnims[stack->ID]->isDead())
  2649. {
  2650. if (!creAnims[stack->ID]->isMoving())
  2651. sorted.hex[stack->getPosition()].alive.push_back(stack);
  2652. else
  2653. {
  2654. // flying creature - just blit them over everyone else
  2655. if (stack->hasBonusOfType(Bonus::FLYING))
  2656. sorted.afterAll.alive.push_back(stack);
  2657. else//try to find current location
  2658. sorted.hex[getCurrentPosition(stack)].alive.push_back(stack);
  2659. }
  2660. }
  2661. else
  2662. sorted.hex[stack->getPosition()].dead.push_back(stack);
  2663. }
  2664. // Sort battle effects (spells)
  2665. for (auto & battleEffect : battleEffects)
  2666. {
  2667. if (battleEffect.position.isValid())
  2668. sorted.hex[battleEffect.position].effects.push_back(&battleEffect);
  2669. else
  2670. sorted.afterAll.effects.push_back(&battleEffect);
  2671. }
  2672. // Sort obstacles
  2673. obstacleController->sortObjectsByHex(sorted);
  2674. // Sort wall parts
  2675. if (siegeController)
  2676. siegeController->sortObjectsByHex(sorted);
  2677. return sorted;
  2678. }
  2679. void CBattleInterface::updateBattleAnimations()
  2680. {
  2681. //handle animations
  2682. for (auto & elem : pendingAnims)
  2683. {
  2684. if (!elem.first) //this animation should be deleted
  2685. continue;
  2686. if (!elem.second)
  2687. {
  2688. elem.second = elem.first->init();
  2689. }
  2690. if (elem.second && elem.first)
  2691. elem.first->nextFrame();
  2692. }
  2693. //delete anims
  2694. int preSize = static_cast<int>(pendingAnims.size());
  2695. for (auto it = pendingAnims.begin(); it != pendingAnims.end(); ++it)
  2696. {
  2697. if (it->first == nullptr)
  2698. {
  2699. pendingAnims.erase(it);
  2700. it = pendingAnims.begin();
  2701. break;
  2702. }
  2703. }
  2704. if (preSize > 0 && pendingAnims.empty())
  2705. {
  2706. //anims ended
  2707. blockUI(activeStack == nullptr);
  2708. animsAreDisplayed.setn(false);
  2709. }
  2710. }
  2711. void CBattleInterface::redrawBackgroundWithHexes(const CStack *activeStack)
  2712. {
  2713. attackableHexes.clear();
  2714. if (activeStack)
  2715. occupyableHexes = curInt->cb->battleGetAvailableHexes(activeStack, true, &attackableHexes);
  2716. auto fillStackCountOutsideHexes = [&]()
  2717. {
  2718. auto accessibility = curInt->cb->getAccesibility();
  2719. for(int i = 0; i < accessibility.size(); i++)
  2720. stackCountOutsideHexes.at(i) = (accessibility[i] == EAccessibility::ACCESSIBLE);
  2721. };
  2722. fillStackCountOutsideHexes();
  2723. //prepare background graphic with hexes and shaded hexes
  2724. blitAt(background, 0, 0, backgroundWithHexes);
  2725. obstacleController->redrawBackgroundWithHexes();
  2726. if (settings["battle"]["stackRange"].Bool())
  2727. {
  2728. std::vector<BattleHex> hexesToShade = occupyableHexes;
  2729. hexesToShade.insert(hexesToShade.end(), attackableHexes.begin(), attackableHexes.end());
  2730. for (BattleHex hex : hexesToShade)
  2731. {
  2732. int i = hex.getY(); //row
  2733. int j = hex.getX()-1; //column
  2734. int x = 58 + (i%2==0 ? 22 : 0) + 44*j;
  2735. int y = 86 + 42 *i;
  2736. SDL_Rect temp_rect = genRect(cellShade->h, cellShade->w, x, y);
  2737. CSDL_Ext::blit8bppAlphaTo24bpp(cellShade, nullptr, backgroundWithHexes, &temp_rect);
  2738. }
  2739. }
  2740. if(settings["battle"]["cellBorders"].Bool())
  2741. CSDL_Ext::blit8bppAlphaTo24bpp(cellBorders, nullptr, backgroundWithHexes, nullptr);
  2742. }