CBattleInterface.cpp 114 KB

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