CBattleInterface.cpp 102 KB

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