CBattleInterface.cpp 115 KB

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