CBattleInterface.cpp 114 KB

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