CBattleInterface.cpp 113 KB

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