CBattleInterface.cpp 115 KB

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