CBattleInterface.cpp 116 KB

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