2
0

CBattleInterface.cpp 112 KB

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