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