CBattleInterface.cpp 115 KB

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