CBattleInterface.cpp 112 KB

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