CBattleInterface.cpp 112 KB

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