CBattleInterface.cpp 114 KB

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