CBattleInterface.cpp 114 KB

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