CBattleInterface.cpp 115 KB

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