CBattleInterface.cpp 104 KB

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