CBattleInterface.cpp 105 KB

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