CBattleInterface.cpp 111 KB

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