CBattleInterface.cpp 112 KB

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