CBattleInterface.cpp 116 KB

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