CBattleInterface.cpp 113 KB

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