CBattleInterface.cpp 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214
  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. const CSpell & spell = *CGI->spellh->spells[spellID];
  1602. spellSelMode = ANY_LOCATION;
  1603. if(spell.getTargetType() == CSpell::CREATURE)
  1604. {
  1605. spellSelMode = selectionTypeByPositiveness(spell);
  1606. }
  1607. if(spell.getTargetType() == CSpell::CREATURE_EXPERT_MASSIVE)
  1608. {
  1609. if(castingHero && castingHero->getSpellSchoolLevel(&spell) < 3)
  1610. spellSelMode = selectionTypeByPositiveness(spell);
  1611. else
  1612. spellSelMode = NO_LOCATION;
  1613. }
  1614. if(spell.getTargetType() == CSpell::OBSTACLE)
  1615. {
  1616. spellSelMode = OBSTACLE;
  1617. }
  1618. if(spell.range[ castingHero->getSpellSchoolLevel(&spell) ] == "X") //spell has no range
  1619. {
  1620. spellSelMode = NO_LOCATION;
  1621. }
  1622. if(spell.id == 63) //teleport
  1623. {
  1624. spellSelMode = TELEPORT;
  1625. }
  1626. if(spell.range[ castingHero->getSpellSchoolLevel(&spell) ].size() > 1) //spell has many-hex range
  1627. {
  1628. spellSelMode = ANY_LOCATION;
  1629. }
  1630. if (spellSelMode == NO_LOCATION) //user does not have to select location
  1631. {
  1632. spellToCast->destinationTile = -1;
  1633. curInt->cb->battleMakeAction(spellToCast);
  1634. endCastingSpell();
  1635. }
  1636. else
  1637. {
  1638. possibleActions.clear();
  1639. possibleActions.push_back (spellSelMode); //only this one actions can be performed at the moment
  1640. GH.fakeMouseMove();//update cursor
  1641. }
  1642. }
  1643. void CBattleInterface::displayEffect(ui32 effect, int destTile)
  1644. {
  1645. addNewAnim(new CSpellEffectAnimation(this, effect, destTile));
  1646. }
  1647. void CBattleInterface::battleTriggerEffect(const BattleTriggerEffect & bte)
  1648. {
  1649. const CStack * stack = curInt->cb->battleGetStackByID(bte.stackID);
  1650. //don't show animation when no HP is regenerated
  1651. switch (bte.effect)
  1652. {
  1653. case Bonus::HP_REGENERATION:
  1654. if( stack->hasBonusOfType(Bonus::HP_REGENERATION) || stack->hasBonusOfType(Bonus::FULL_HP_REGENERATION))
  1655. {
  1656. displayEffect(74, stack->position);
  1657. CCS->soundh->playSound(soundBase::REGENER);
  1658. }
  1659. break;
  1660. case Bonus::MANA_DRAIN:
  1661. displayEffect(77, stack->position);
  1662. CCS->soundh->playSound(soundBase::MANADRAI);
  1663. break;
  1664. case Bonus::POISON:
  1665. displayEffect(67, stack->position);
  1666. CCS->soundh->playSound(soundBase::POISON);
  1667. break;
  1668. case Bonus::FEAR:
  1669. displayEffect(15, stack->position);
  1670. CCS->soundh->playSound(soundBase::FEAR);
  1671. break;
  1672. case Bonus::MORALE:
  1673. {
  1674. std::string hlp = CGI->generaltexth->allTexts[33];
  1675. boost::algorithm::replace_first(hlp,"%s",(stack->getName()));
  1676. displayEffect(20,stack->position);
  1677. console->addText(hlp);
  1678. break;
  1679. }
  1680. default:
  1681. return;
  1682. }
  1683. //waitForAnims(); //fixme: freezes game :?
  1684. }
  1685. void CBattleInterface::setAnimSpeed(int set)
  1686. {
  1687. Settings speed = settings.write["battle"]["animationSpeed"];
  1688. speed->Float() = set;
  1689. }
  1690. int CBattleInterface::getAnimSpeed() const
  1691. {
  1692. return settings["battle"]["animationSpeed"].Float();
  1693. }
  1694. void CBattleInterface::activateStack()
  1695. {
  1696. activeStack = stackToActivate;
  1697. stackToActivate = NULL;
  1698. const CStack *s = activeStack;
  1699. myTurn = true;
  1700. if(attackerInt && defenderInt) //hotseat -> need to pick which interface "takes over" as active
  1701. curInt = attackerInt->playerID == s->owner ? attackerInt : defenderInt;
  1702. queue->update();
  1703. redrawBackgroundWithHexes(activeStack);
  1704. bWait->block(vstd::contains(s->state, EBattleStackState::WAITING)); //block waiting button if stack has been already waiting
  1705. //block cast spell button if hero doesn't have a spellbook
  1706. bSpell->block(!curInt->cb->battleCanCastSpell());
  1707. bSurrender->block((curInt == attackerInt ? defendingHeroInstance : attackingHeroInstance) == NULL);
  1708. bFlee->block(!curInt->cb->battleCanFlee());
  1709. bSurrender->block(curInt->cb->battleGetSurrenderCost() < 0);
  1710. //set casting flag to true if creature can use it to not check it every time
  1711. const Bonus *spellcaster = s->getBonus(Selector::type(Bonus::SPELLCASTER)),
  1712. *randomSpellcaster = s->getBonus(Selector::type(Bonus::RANDOM_SPELLCASTER));
  1713. if (s->casts && (spellcaster || randomSpellcaster))
  1714. {
  1715. stackCanCastSpell = true;
  1716. if(randomSpellcaster)
  1717. creatureSpellToCast = curInt->cb->battleGetRandomStackSpell(s, CBattleInfoCallback::RANDOM_AIMED); //faerie dragon can cast only one spell until their next move
  1718. else
  1719. creatureSpellToCast = spellcaster->subtype;
  1720. if(creatureSpellToCast < 0) //TODO proper way of detecting casters of positive spells
  1721. spellSelMode = FRIENDLY_CREATURE;
  1722. else
  1723. spellSelMode = selectionTypeByPositiveness(*CGI->spellh->spells[creatureSpellToCast]);
  1724. }
  1725. else
  1726. {
  1727. stackCanCastSpell = false;
  1728. creatureSpellToCast = -1;
  1729. }
  1730. GH.fakeMouseMove();
  1731. if(!pendingAnims.size() && !active)
  1732. activate();
  1733. }
  1734. double CBattleInterface::getAnimSpeedMultiplier() const
  1735. {
  1736. switch(getAnimSpeed())
  1737. {
  1738. case 1:
  1739. return 3.5;
  1740. case 2:
  1741. return 2.2;
  1742. case 4:
  1743. return 1.0;
  1744. default:
  1745. return 0.0;
  1746. }
  1747. }
  1748. void CBattleInterface::endCastingSpell()
  1749. {
  1750. assert(spellDestSelectMode);
  1751. delete spellToCast;
  1752. spellToCast = NULL;
  1753. spellDestSelectMode = false;
  1754. CCS->curh->changeGraphic(1, 6);
  1755. //restore actions for current stack
  1756. possibleActions.clear();
  1757. getPossibleActionsForStack (activeStack);
  1758. }
  1759. void CBattleInterface::getPossibleActionsForStack(const CStack * stack)
  1760. {
  1761. //first action will be prioritized over later ones
  1762. if (stack->casts) //TODO: check for battlefield effects that prevent casting?
  1763. {
  1764. if (stack->hasBonusOfType (Bonus::SPELLCASTER))
  1765. {
  1766. //TODO: poll possible spells
  1767. BOOST_FOREACH (Bonus * spellBonus, *stack->getBonuses (Selector::type(Bonus::SPELLCASTER)))
  1768. {
  1769. possibleActions.push_back (selectionTypeByPositiveness (*CGI->spellh->spells[spellBonus->subtype]));
  1770. }
  1771. //TODO: determine whether spell is rising
  1772. //possibleActions.push_back (RISING_SPELL);
  1773. //possibleActions.push_back (OBSTACLE);
  1774. //possibleActions.push_back (SACRIFICE);
  1775. //possibleActions.push_back (NO_LOCATION);
  1776. //possibleActions.push_back (ANY_LOCATION);
  1777. //possibleActions.push_back (OTHER_SPELL);
  1778. }
  1779. if (stack->hasBonusOfType (Bonus::RANDOM_SPELLCASTER))
  1780. possibleActions.push_back (RANDOM_GENIE_SPELL);
  1781. if (stack->hasBonusOfType (Bonus::DAEMON_SUMMONING))
  1782. possibleActions.push_back (RISE_DEMONS);
  1783. }
  1784. if (stack->shots && stack->hasBonusOfType (Bonus::SHOOTER))
  1785. possibleActions.push_back (SHOOT);
  1786. if (stack->hasBonusOfType (Bonus::RETURN_AFTER_STRIKE));
  1787. possibleActions.push_back (ATTACK_AND_RETURN);
  1788. possibleActions.push_back(ATTACK); //all active stacks can attack
  1789. possibleActions.push_back(WALK_AND_ATTACK); //not all stacks can always walk, but we will check this elsewhere
  1790. if (siegeH && stack->hasBonusOfType (Bonus::CATAPULT)) //TODO: check shots
  1791. possibleActions.push_back (CATAPULT);
  1792. if (stack->hasBonusOfType (Bonus::HEALER))
  1793. possibleActions.push_back (HEAL);
  1794. }
  1795. void CBattleInterface::showAliveStack(const CStack *stack, SDL_Surface * to)
  1796. {
  1797. int ID = stack->ID;
  1798. if(creAnims.find(ID) == creAnims.end()) //eg. for summoned but not yet handled stacks
  1799. return;
  1800. const CCreature *creature = stack->getCreature();
  1801. SDL_Rect unitRect = {creAnims[ID]->pos.x, creAnims[ID]->pos.y, uint16_t(creAnims[ID]->fullWidth), uint16_t(creAnims[ID]->fullHeight)};
  1802. int animType = creAnims[ID]->getType();
  1803. int affectingSpeed = getAnimSpeed();
  1804. if(animType == 1 || animType == 2) //standing stacks should not stand faster :)
  1805. affectingSpeed = 2;
  1806. bool incrementFrame = (animCount%(4/affectingSpeed)==0) && animType!=5 && animType!=20 && animType!=2;
  1807. if (creature->idNumber == 149)
  1808. {
  1809. // a turret creature has a limited height, so cut it at a certain position; turret creature has no standing anim
  1810. unitRect.h = graphics->wallPositions[siegeH->town->town->typeID][20].y;
  1811. }
  1812. else
  1813. {
  1814. // standing animation
  1815. if(animType == 2)
  1816. {
  1817. if(standingFrame.find(ID)!=standingFrame.end())
  1818. {
  1819. incrementFrame = (animCount%(8/affectingSpeed)==0);
  1820. if(incrementFrame)
  1821. {
  1822. ++standingFrame[ID];
  1823. if(standingFrame[ID] == creAnims[ID]->framesInGroup(CCreatureAnim::HOLDING))
  1824. {
  1825. standingFrame.erase(standingFrame.find(ID));
  1826. }
  1827. }
  1828. }
  1829. else
  1830. {
  1831. if((rand()%50) == 0)
  1832. {
  1833. standingFrame.insert(std::make_pair(ID, 0));
  1834. }
  1835. }
  1836. }
  1837. }
  1838. // As long as the projectile of the shooter-stack is flying incrementFrame should be false
  1839. //bool shootingFinished = true;
  1840. for (std::list<ProjectileInfo>::iterator it = projectiles.begin(); it != projectiles.end(); ++it)
  1841. {
  1842. if (it->stackID == ID)
  1843. {
  1844. //shootingFinished = false;
  1845. if (it->animStartDelay == 0)
  1846. incrementFrame = false;
  1847. }
  1848. }
  1849. // Increment always when moving, never if stack died
  1850. creAnims[ID]->nextFrame(to, unitRect.x, unitRect.y, creDir[ID], animCount, incrementFrame, activeStack && ID==activeStack->ID, ID==mouseHoveredStack, &unitRect);
  1851. //printing amount
  1852. if(stack->count > 0 //don't print if stack is not alive
  1853. && (!curInt->curAction
  1854. || (curInt->curAction->stackNumber != ID //don't print if stack is currently taking an action
  1855. && (curInt->curAction->actionType != BattleAction::WALK_AND_ATTACK || stack->position != curInt->curAction->additionalInfo) //nor if it's an object of attack
  1856. && (curInt->curAction->destinationTile != stack->position) //nor if it's on destination tile for current action
  1857. )
  1858. )
  1859. && !stack->hasBonusOfType(Bonus::SIEGE_WEAPON) //and not a war machine...
  1860. )
  1861. {
  1862. const BattleHex nextPos = stack->position + (stack->attackerOwned ? 1 : -1);
  1863. const bool edge = stack->position % GameConstants::BFIELD_WIDTH == (stack->attackerOwned ? GameConstants::BFIELD_WIDTH - 2 : 1);
  1864. const bool moveInside = !edge && !stackCountOutsideHexes[nextPos];
  1865. int xAdd = (stack->attackerOwned ? 220 : 202) +
  1866. (stack->doubleWide() ? 44 : 0) * (stack->attackerOwned ? +1 : -1) +
  1867. (moveInside ? amountNormal->w + 10 : 0) * (stack->attackerOwned ? -1 : +1);
  1868. int yAdd = 260 + ((stack->attackerOwned || moveInside) ? 0 : -15);
  1869. //blitting amount background box
  1870. SDL_Surface *amountBG = NULL;
  1871. TBonusListPtr spellEffects = stack->getSpellBonuses();
  1872. if(!spellEffects->size())
  1873. {
  1874. amountBG = amountNormal;
  1875. }
  1876. else
  1877. {
  1878. int pos=0; //determining total positiveness of effects
  1879. std::vector<si32> spellIds = stack->activeSpells();
  1880. for(std::vector<si32>::const_iterator it = spellIds.begin(); it != spellIds.end(); it++)
  1881. {
  1882. pos += CGI->spellh->spells[ *it ]->positiveness;
  1883. }
  1884. if(pos > 0)
  1885. {
  1886. amountBG = amountPositive;
  1887. }
  1888. else if(pos < 0)
  1889. {
  1890. amountBG = amountNegative;
  1891. }
  1892. else
  1893. {
  1894. amountBG = amountEffNeutral;
  1895. }
  1896. }
  1897. SDL_Rect temp_rect = genRect(amountNormal->h, amountNormal->w, creAnims[ID]->pos.x + xAdd, creAnims[ID]->pos.y + yAdd);
  1898. SDL_BlitSurface(amountBG, NULL, to, &temp_rect);
  1899. //blitting amount
  1900. CSDL_Ext::printAtMiddle(
  1901. makeNumberShort(stack->count),
  1902. creAnims[ID]->pos.x + xAdd + 15,
  1903. creAnims[ID]->pos.y + yAdd + 5,
  1904. FONT_TINY,
  1905. Colors::Cornsilk,
  1906. to
  1907. );
  1908. }
  1909. }
  1910. void CBattleInterface::showPieceOfWall(SDL_Surface * to, int hex, const std::vector<const CStack*> & stacks)
  1911. {
  1912. if(!siegeH)
  1913. return;
  1914. using namespace boost::assign;
  1915. #ifdef CPP11_USE_INITIALIZERS_LIST
  1916. //note - std::list<int> must be specified to avoid type deduction by gcc (may not work in other compilers)
  1917. static const std::map<int, std::list<int> > hexToPart = {
  1918. {12, std::list<int>{8, 1, 7}}, {45, std::list<int>{12, 6}},
  1919. {101, std::list<int>{10}}, {118, std::list<int>{2}},
  1920. {165, std::list<int>{11}}, {186, std::list<int>{3}}};
  1921. #else
  1922. 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))
  1923. (101, list_of<int>(10))(118, list_of<int>(2))(165, list_of<int>(11))(186, list_of<int>(3));
  1924. #endif
  1925. std::map<int, std::list<int> >::const_iterator it = hexToPart.find(hex);
  1926. if(it != hexToPart.end())
  1927. {
  1928. BOOST_FOREACH(int wallNum, it->second)
  1929. {
  1930. siegeH->printPartOfWall(to, wallNum);
  1931. //print creature in turret
  1932. int posToSeek = -1;
  1933. switch(wallNum)
  1934. {
  1935. case 3: //bottom turret
  1936. posToSeek = -3;
  1937. break;
  1938. case 8: //upper turret
  1939. posToSeek = -4;
  1940. break;
  1941. case 2: //keep
  1942. posToSeek = -2;
  1943. break;
  1944. }
  1945. if(posToSeek != -1)
  1946. {
  1947. const CStack *turret = NULL;
  1948. BOOST_FOREACH(const CStack *s, stacks)
  1949. {
  1950. if(s->position == posToSeek)
  1951. {
  1952. turret = s;
  1953. break;
  1954. }
  1955. }
  1956. if(turret)
  1957. {
  1958. showAliveStack(turret, to);
  1959. //blitting creature cover
  1960. switch(posToSeek)
  1961. {
  1962. case -3: //bottom turret
  1963. siegeH->printPartOfWall(to, 16);
  1964. break;
  1965. case -4: //upper turret
  1966. siegeH->printPartOfWall(to, 17);
  1967. break;
  1968. case -2: //keep
  1969. siegeH->printPartOfWall(to, 15);
  1970. break;
  1971. }
  1972. }
  1973. }
  1974. }
  1975. }
  1976. // Damaged wall below gate have to be drawn earlier than a non-damaged wall below gate.
  1977. if ((hex == 112 && curInt->cb->battleGetWallState(3) == 3) || (hex == 147 && curInt->cb->battleGetWallState(3) != 3))
  1978. siegeH->printPartOfWall(to, 5);
  1979. // Damaged bottom wall have to be drawn earlier than a non-damaged bottom wall.
  1980. if ((hex == 165 && curInt->cb->battleGetWallState(4) == 3) || (hex == 185 && curInt->cb->battleGetWallState(4) != 3))
  1981. siegeH->printPartOfWall(to, 4);
  1982. }
  1983. void CBattleInterface::redrawBackgroundWithHexes(const CStack * activeStack)
  1984. {
  1985. attackableHexes.clear();
  1986. if (activeStack)
  1987. occupyableHexes = curInt->cb->battleGetAvailableHexes(activeStack, true, &attackableHexes);
  1988. curInt->cb->battleGetStackCountOutsideHexes(stackCountOutsideHexes);
  1989. //preparating background graphic with hexes and shaded hexes
  1990. blitAt(background, 0, 0, backgroundWithHexes);
  1991. if(settings["battle"]["cellBorders"].Bool())
  1992. CSDL_Ext::blit8bppAlphaTo24bpp(cellBorders, NULL, backgroundWithHexes, NULL);
  1993. if(settings["battle"]["stackRange"].Bool())
  1994. {
  1995. std::vector<BattleHex> hexesToShade = occupyableHexes;
  1996. hexesToShade.insert(hexesToShade.end(), attackableHexes.begin(), attackableHexes.end());
  1997. BOOST_FOREACH(BattleHex hex, hexesToShade)
  1998. {
  1999. int i = hex.getY(); //row
  2000. int j = hex.getX()-1; //column
  2001. int x = 58 + (i%2==0 ? 22 : 0) + 44*j;
  2002. int y = 86 + 42 * i;
  2003. SDL_Rect temp_rect = genRect(cellShade->h, cellShade->w, x, y);
  2004. CSDL_Ext::blit8bppAlphaTo24bpp(cellShade, NULL, backgroundWithHexes, &temp_rect);
  2005. }
  2006. }
  2007. }
  2008. void CBattleInterface::printConsoleAttacked( const CStack * defender, int dmg, int killed, const CStack * attacker, bool multiple )
  2009. {
  2010. char tabh[200];
  2011. int end = 0;
  2012. if (attacker) //ignore if stacks were killed by spell
  2013. {
  2014. end = sprintf(tabh, CGI->generaltexth->allTexts[attacker->count > 1 ? 377 : 376].c_str(),
  2015. (attacker->count > 1 ? attacker->getCreature()->namePl.c_str() : attacker->getCreature()->nameSing.c_str()), dmg);
  2016. }
  2017. if(killed > 0)
  2018. {
  2019. if(killed > 1)
  2020. {
  2021. sprintf(tabh + end, CGI->generaltexth->allTexts[379].c_str(), killed,
  2022. multiple ? CGI->generaltexth->allTexts[43].c_str() : defender->getCreature()->namePl.c_str()); // creatures perish
  2023. }
  2024. else //killed == 1
  2025. {
  2026. sprintf(tabh + end, CGI->generaltexth->allTexts[378].c_str(),
  2027. multiple ? CGI->generaltexth->allTexts[42].c_str() : defender->getCreature()->nameSing.c_str()); // creature perishes
  2028. }
  2029. }
  2030. console->addText(std::string(tabh));
  2031. }
  2032. void CBattleInterface::projectileShowHelper(SDL_Surface * to)
  2033. {
  2034. if(to == NULL)
  2035. to = screen;
  2036. std::list< std::list<ProjectileInfo>::iterator > toBeDeleted;
  2037. for(std::list<ProjectileInfo>::iterator it=projectiles.begin(); it!=projectiles.end(); ++it)
  2038. {
  2039. // Creature have to be in a shooting anim and the anim start delay must be over.
  2040. // Otherwise abort to start moving the projectile.
  2041. if (it->animStartDelay > 0)
  2042. {
  2043. if(it->animStartDelay == creAnims[it->stackID]->getAnimationFrame() + 1
  2044. && creAnims[it->stackID]->getType() >= 14 && creAnims[it->stackID]->getType() <= 16)
  2045. it->animStartDelay = 0;
  2046. else
  2047. continue;
  2048. }
  2049. SDL_Rect dst;
  2050. dst.h = idToProjectile[it->creID]->ourImages[it->frameNum].bitmap->h;
  2051. dst.w = idToProjectile[it->creID]->ourImages[it->frameNum].bitmap->w;
  2052. dst.x = it->x;
  2053. dst.y = it->y;
  2054. // The equation below calculates the center pos of the canon, but we need the top left pos
  2055. // of it for drawing
  2056. if (it->catapultInfo)
  2057. {
  2058. dst.x -= 17.;
  2059. dst.y -= 10.;
  2060. }
  2061. if(it->reverse)
  2062. {
  2063. SDL_Surface * rev = CSDL_Ext::rotate01(idToProjectile[it->creID]->ourImages[it->frameNum].bitmap);
  2064. CSDL_Ext::blit8bppAlphaTo24bpp(rev, NULL, to, &dst);
  2065. SDL_FreeSurface(rev);
  2066. }
  2067. else
  2068. {
  2069. CSDL_Ext::blit8bppAlphaTo24bpp(idToProjectile[it->creID]->ourImages[it->frameNum].bitmap, NULL, to, &dst);
  2070. }
  2071. // Update projectile
  2072. ++it->step;
  2073. if(it->step == it->lastStep)
  2074. {
  2075. toBeDeleted.insert(toBeDeleted.end(), it);
  2076. }
  2077. else
  2078. {
  2079. if (it->catapultInfo)
  2080. {
  2081. // Parabolic shot of the trajectory, as follows: f(x) = ax^2 + bx + c
  2082. it->x += it->dx;
  2083. it->y = it->catapultInfo->calculateY(it->x - this->pos.x) + this->pos.y;
  2084. }
  2085. else
  2086. {
  2087. // Normal projectile, just add the calculated "deltas" to the x and y positions.
  2088. it->x += it->dx;
  2089. it->y += it->dy;
  2090. }
  2091. if(it->spin)
  2092. {
  2093. ++(it->frameNum);
  2094. it->frameNum %= idToProjectile[it->creID]->ourImages.size();
  2095. }
  2096. }
  2097. }
  2098. for(std::list< std::list<ProjectileInfo>::iterator >::iterator it = toBeDeleted.begin(); it!= toBeDeleted.end(); ++it)
  2099. {
  2100. projectiles.erase(*it);
  2101. }
  2102. }
  2103. void CBattleInterface::endAction(const BattleAction* action)
  2104. {
  2105. const CStack * stack = curInt->cb->battleGetStackByID(action->stackNumber);
  2106. //if((action->actionType==2 || (action->actionType==6 && action->destinationTile!=cb->battleGetPos(action->stackNumber)))) //activating interface when move is finished
  2107. // {
  2108. // activate();
  2109. // }
  2110. if(action->actionType == BattleAction::HERO_SPELL)
  2111. {
  2112. if(action->side)
  2113. defendingHero->setPhase(0);
  2114. else
  2115. attackingHero->setPhase(0);
  2116. }
  2117. if(action->actionType == BattleAction::WALK && creAnims[action->stackNumber]->getType() != 2) //walk or walk & attack
  2118. {
  2119. pendingAnims.push_back(std::make_pair(new CMovementEndAnimation(this, stack, action->destinationTile), false));
  2120. }
  2121. if(action->actionType == BattleAction::CATAPULT) //catapult
  2122. {
  2123. }
  2124. //check if we should reverse stacks
  2125. //for some strange reason, it's not enough
  2126. // std::set<const CStack *> stacks;
  2127. // stacks.insert(LOCPLINT->cb->battleGetStackByID(action->stackNumber));
  2128. // stacks.insert(LOCPLINT->cb->battleGetStackByPos(action->destinationTile));
  2129. TStacks stacks = curInt->cb->battleGetStacks(CBattleCallback::MINE_AND_ENEMY);
  2130. BOOST_FOREACH(const CStack *s, stacks)
  2131. {
  2132. if(s && creDir[s->ID] != bool(s->attackerOwned) && s->alive())
  2133. {
  2134. addNewAnim(new CReverseAnimation(this, s, s->position, false));
  2135. }
  2136. }
  2137. queue->update();
  2138. if(tacticsMode) //stack ended movement in tactics phase -> select the next one
  2139. bTacticNextStack(stack);
  2140. 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
  2141. redrawBackgroundWithHexes(activeStack);
  2142. }
  2143. void CBattleInterface::hideQueue()
  2144. {
  2145. Settings showQueue = settings.write["battle"]["showQueue"];
  2146. showQueue->Bool() = false;
  2147. queue->deactivate();
  2148. if(!queue->embedded)
  2149. {
  2150. moveBy(Point(0, -queue->pos.h / 2));
  2151. GH.totalRedraw();
  2152. }
  2153. }
  2154. void CBattleInterface::showQueue()
  2155. {
  2156. Settings showQueue = settings.write["battle"]["showQueue"];
  2157. showQueue->Bool() = true;
  2158. queue->activate();
  2159. if(!queue->embedded)
  2160. {
  2161. moveBy(Point(0, +queue->pos.h / 2));
  2162. GH.totalRedraw();
  2163. }
  2164. }
  2165. void CBattleInterface::startAction(const BattleAction* action)
  2166. {
  2167. if(action->actionType == BattleAction::END_TACTIC_PHASE)
  2168. {
  2169. SDL_FreeSurface(menu);
  2170. menu = BitmapHandler::loadBitmap("CBAR.bmp");
  2171. graphics->blueToPlayersAdv(menu, curInt->playerID);
  2172. bDefence->block(false);
  2173. bWait->block(false);
  2174. if(active)
  2175. {
  2176. if(btactEnd && btactNext) //if the other side had tactics, there are no buttons
  2177. {
  2178. btactEnd->deactivate();
  2179. btactNext->deactivate();
  2180. bConsoleDown->activate();
  2181. bConsoleUp->activate();
  2182. }
  2183. }
  2184. redraw();
  2185. return;
  2186. }
  2187. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  2188. if(stack)
  2189. {
  2190. queue->update();
  2191. }
  2192. else
  2193. {
  2194. assert(action->actionType == BattleAction::HERO_SPELL); //only cast spell is valid action without acting stack number
  2195. }
  2196. if(action->actionType == BattleAction::WALK
  2197. || (action->actionType == BattleAction::WALK_AND_ATTACK && action->destinationTile != stack->position))
  2198. {
  2199. moveStarted = true;
  2200. if(creAnims[action->stackNumber]->framesInGroup(CCreatureAnim::MOVE_START))
  2201. {
  2202. const CStack * stack = curInt->cb->battleGetStackByID(action->stackNumber);
  2203. pendingAnims.push_back(std::make_pair(new CMovementStartAnimation(this, stack), false));
  2204. }
  2205. }
  2206. if(active)
  2207. deactivate();
  2208. char txt[400];
  2209. if(action->actionType == BattleAction::HERO_SPELL) //when hero casts spell
  2210. {
  2211. if(action->side)
  2212. defendingHero->setPhase(4);
  2213. else
  2214. attackingHero->setPhase(4);
  2215. return;
  2216. }
  2217. if(!stack)
  2218. {
  2219. tlog1<<"Something wrong with stackNumber in actionStarted. Stack number: "<<action->stackNumber<<std::endl;
  2220. return;
  2221. }
  2222. int txtid = 0;
  2223. switch(action->actionType)
  2224. {
  2225. case BattleAction::WAIT:
  2226. txtid = 136;
  2227. break;
  2228. case BattleAction::BAD_MORALE:
  2229. txtid = -34; //negative -> no separate singular/plural form
  2230. displayEffect(30,stack->position);
  2231. break;
  2232. }
  2233. if(txtid > 0 && stack->count != 1)
  2234. txtid++; //move to plural text
  2235. else if(txtid < 0)
  2236. txtid = -txtid;
  2237. if(txtid)
  2238. {
  2239. sprintf(txt, CGI->generaltexth->allTexts[txtid].c_str(), (stack->count != 1) ? stack->getCreature()->namePl.c_str() : stack->getCreature()->nameSing.c_str(), 0);
  2240. console->addText(txt);
  2241. }
  2242. //displaying special abilities
  2243. switch (action->actionType)
  2244. {
  2245. case BattleAction::STACK_HEAL:
  2246. displayEffect(74, action->destinationTile);
  2247. CCS->soundh->playSound(soundBase::REGENER);
  2248. break;
  2249. }
  2250. }
  2251. void CBattleInterface::waitForAnims()
  2252. {
  2253. auto unlockPim = vstd::makeUnlockGuard(*LOCPLINT->pim);
  2254. animsAreDisplayed.waitWhileTrue();
  2255. }
  2256. void CBattleInterface::bEndTacticPhase()
  2257. {
  2258. activeStack = NULL;
  2259. btactEnd->block(true);
  2260. tacticsMode = false;
  2261. }
  2262. static bool immobile(const CStack *s)
  2263. {
  2264. return !s->Speed(0, true); //should bound stacks be immobile?
  2265. }
  2266. void CBattleInterface::bTacticNextStack(const CStack *current /*= NULL*/)
  2267. {
  2268. if(!current)
  2269. current = activeStack;
  2270. //no switching stacks when the current one is moving
  2271. waitForAnims();
  2272. TStacks stacksOfMine = tacticianInterface->cb->battleGetStacks(CBattleCallback::ONLY_MINE);
  2273. stacksOfMine.erase(std::remove_if(stacksOfMine.begin(), stacksOfMine.end(), &immobile), stacksOfMine.end());
  2274. TStacks::iterator it = vstd::find(stacksOfMine, current);
  2275. if(it != stacksOfMine.end() && ++it != stacksOfMine.end())
  2276. stackActivated(*it);
  2277. else
  2278. stackActivated(stacksOfMine.front());
  2279. possibleActions.clear();
  2280. possibleActions += MOVE_TACTICS, CHOOSE_TACTICS_STACK;
  2281. }
  2282. CBattleInterface::PossibleActions CBattleInterface::selectionTypeByPositiveness(const CSpell & spell)
  2283. {
  2284. switch(spell.positiveness)
  2285. {
  2286. case CSpell::NEGATIVE :
  2287. return HOSTILE_CREATURE;
  2288. case CSpell::NEUTRAL:
  2289. return ANY_CREATURE;
  2290. case CSpell::POSITIVE:
  2291. return FRIENDLY_CREATURE;
  2292. }
  2293. assert(0);
  2294. return NO_LOCATION; //should never happen
  2295. }
  2296. std::string formatDmgRange(std::pair<ui32, ui32> dmgRange)
  2297. {
  2298. if(dmgRange.first != dmgRange.second)
  2299. return (boost::format("%d - %d") % dmgRange.first % dmgRange.second).str();
  2300. else
  2301. return (boost::format("%d") % dmgRange.first).str();
  2302. }
  2303. void CBattleInterface::handleHex(BattleHex myNumber, int eventType)
  2304. {
  2305. if(!myTurn) //we are not permit to do anything
  2306. return;
  2307. // This function handles mouse move over hexes and l-clicking on them.
  2308. // First we decide what happens if player clicks on this hex and set appropriately
  2309. // consoleMsg, cursorFrame/Type and prepare lambda realizeAction.
  2310. //
  2311. // Then, depending whether it was hover/click we either call the action or set tooltip/cursor.
  2312. //used when hovering -> tooltip message and cursor to be set
  2313. std::string consoleMsg;
  2314. bool setCursor = true; //if we want to suppress setting cursor
  2315. int cursorType = ECursor::COMBAT, cursorFrame = ECursor::COMBAT_POINTER;
  2316. //used when l-clicking -> action to be called upon the click
  2317. std::function<void()> realizeAction;
  2318. //helper lambda that appropriately realizes action / sets cursor and tooltip
  2319. //TODO: separate action at mouse move and clicking
  2320. auto realizeThingsToDo = [&]()
  2321. {
  2322. if(eventType == MOVE)
  2323. {
  2324. if(setCursor)
  2325. CCS->curh->changeGraphic(cursorType, cursorFrame);
  2326. this->console->alterText(consoleMsg);
  2327. this->console->whoSetAlter = 0;
  2328. }
  2329. if(eventType == LCLICK && realizeAction)
  2330. {
  2331. realizeAction();
  2332. CCS->curh->changeGraphic(ECursor::COMBAT, ECursor::COMBAT_POINTER);
  2333. this->console->alterText("");
  2334. }
  2335. };
  2336. const CStack * const shere = curInt->cb->battleGetStackByPos(myNumber, false);
  2337. const CStack * const sactive = activeStack;
  2338. if (!sactive)
  2339. return;
  2340. bool ourStack = false;
  2341. if (shere)
  2342. ourStack = shere->owner == curInt->playerID;
  2343. bool noStackIsHovered = true; //will cause removing a blue glow
  2344. localActions.clear();
  2345. BOOST_FOREACH (PossibleActions action, possibleActions)
  2346. {
  2347. bool legalAction = false;
  2348. bool illegalAction = false;
  2349. //TODO: copy actions avaliable to perform at this hex to localActions. set currentAction
  2350. switch (action)
  2351. {
  2352. case MOVE_TACTICS:
  2353. break;
  2354. case CHOOSE_TACTICS_STACK:
  2355. if (shere && ourStack)
  2356. legalAction = true;
  2357. break;
  2358. case MOVE_STACK:
  2359. if (vstd::contains(occupyableHexes, myNumber) || activeStack->coversPos(myNumber))
  2360. //TODO
  2361. legalAction = true;
  2362. break;
  2363. case ATTACK:
  2364. case WALK_AND_ATTACK:
  2365. case ATTACK_AND_RETURN:
  2366. {
  2367. std::vector<BattleHex> acc = curInt->cb->battleGetAvailableHexes (activeStack, false);
  2368. BattleHex attackFromHex = fromWhichHexAttack(myNumber);
  2369. if(shere->alive() && isTileAttackable(myNumber) && attackFromHex >= 0) //we can be in this line when unreachable creature is L - clicked (as of revision 1308)
  2370. legalAction = true;
  2371. }
  2372. break;
  2373. case SHOOT:
  2374. if(curInt->cb->battleCanShoot (activeStack, myNumber))
  2375. legalAction = true;
  2376. break;
  2377. case HOSTILE_CREATURE: //TODO: check spell immunity
  2378. if (shere && !ourStack && isCastingPossibleHere (sactive, shere, myNumber))
  2379. legalAction = true;
  2380. break;
  2381. case FRIENDLY_CREATURE:
  2382. if (shere && ourStack && isCastingPossibleHere (sactive, shere, myNumber))
  2383. legalAction = true;
  2384. break;
  2385. case RISING_SPELL:
  2386. if (shere && shere->canBeHealed() && isCastingPossibleHere (sactive, shere, myNumber)) //TODO: at least one stack has to be raised by resurrection / animate dead
  2387. legalAction = true;
  2388. break;
  2389. case RANDOM_GENIE_SPELL:
  2390. {
  2391. if (shere)
  2392. {
  2393. int spellID = curInt->cb->battleGetRandomStackSpell(shere, CBattleInfoCallback::RANDOM_GENIE);
  2394. if (spellID > -1)
  2395. {
  2396. sp = CGI->spellh->spells[spellID];
  2397. legalAction = true;
  2398. }
  2399. }
  2400. }
  2401. break;
  2402. case OBSTACLE:
  2403. legalAction = false; //TODO
  2404. break;
  2405. case TELEPORT:
  2406. {
  2407. const ui8 skill = spellToCast ? getActiveHero()->getSpellSchoolLevel(CGI->spellh->spells[spellToCast->additionalInfo]) : 0; //skill level
  2408. //TODO: creature can cast a spell with some skill / spellpower as well
  2409. //TODO: explicitely save spell_to_cast * CSpell, power, skill
  2410. if (curInt->cb->battleCanTeleportTo(activeStack, myNumber, skill))
  2411. legalAction = true;
  2412. else
  2413. illegalAction = true;
  2414. }
  2415. break;
  2416. case OTHER_SPELL: //TODO
  2417. break;
  2418. case CATAPULT:
  2419. if (isCatapultAttackable(myNumber))
  2420. legalAction = true;
  2421. break;
  2422. case HEAL:
  2423. if (shere && ourStack && shere->canBeHealed())
  2424. legalAction = true;
  2425. break;
  2426. case RISE_DEMONS:
  2427. if (shere && ourStack && !shere->alive())
  2428. legalAction = true;
  2429. break;
  2430. }
  2431. if (legalAction)
  2432. localActions.push_back (action);
  2433. else if (illegalAction)
  2434. illegalActions.push_back (action);
  2435. }
  2436. if (vstd::contains(localActions, selectedAction)) //try to use last selected action by default
  2437. currentAction = selectedAction;
  2438. else if (localActions.size()) //if not possible, select first avaliable action 9they are sorted by suggested priority)
  2439. currentAction = localActions.front();
  2440. else //no legal action possible
  2441. {
  2442. currentAction = INVALID; //don't allow to do anything
  2443. if (vstd::contains(illegalActions, selectedAction))
  2444. illegalAction = selectedAction;
  2445. else if (illegalActions.size())
  2446. illegalAction = illegalActions.front();
  2447. else
  2448. illegalAction = INVALID; //we should never be here
  2449. }
  2450. bool isCastingPossible = false;
  2451. if (currentAction > INVALID)
  2452. {
  2453. switch (currentAction) //display console message, realize selected action
  2454. {
  2455. case CHOOSE_TACTICS_STACK:
  2456. consoleMsg = (boost::format(CGI->generaltexth->allTexts[481]) % shere->getName()).str(); //Select %s
  2457. realizeAction = [=]{ stackActivated(shere); };
  2458. break;
  2459. case MOVE:
  2460. if(activeStack->hasBonusOfType(Bonus::FLYING))
  2461. {
  2462. cursorFrame = ECursor::COMBAT_FLY;
  2463. consoleMsg = (boost::format(CGI->generaltexth->allTexts[295]) % activeStack->getName()).str(); //Fly %s here
  2464. }
  2465. else
  2466. {
  2467. cursorFrame = ECursor::COMBAT_MOVE;
  2468. consoleMsg = (boost::format(CGI->generaltexth->allTexts[294]) % activeStack->getName()).str(); //Move %s here
  2469. }
  2470. realizeAction = [=]
  2471. {
  2472. if(activeStack->doubleWide())
  2473. {
  2474. std::vector<BattleHex> acc = curInt->cb->battleGetAvailableHexes(activeStack, false);
  2475. int shiftedDest = myNumber + (activeStack->attackerOwned ? 1 : -1);
  2476. if(vstd::contains(acc, myNumber))
  2477. giveCommand (BattleAction::WALK ,myNumber, activeStack->ID);
  2478. else if(vstd::contains(acc, shiftedDest))
  2479. giveCommand (BattleAction::WALK, shiftedDest, activeStack->ID);
  2480. }
  2481. else
  2482. {
  2483. giveCommand(BattleAction::WALK, myNumber, activeStack->ID);
  2484. }
  2485. };
  2486. break;
  2487. case ATTACK:
  2488. case WALK_AND_ATTACK:
  2489. case ATTACK_AND_RETURN: //TODO: allow to disable return
  2490. {
  2491. setBattleCursor(myNumber); //handle direction of cursor and attackable tile
  2492. setCursor = false; //don't overwrite settings from the call above
  2493. realizeAction = [=]
  2494. {
  2495. BattleHex attackFromHex = fromWhichHexAttack(myNumber);
  2496. if(attackFromHex >= 0) //we can be in this line when unreachable creature is L - clicked (as of revision 1308)
  2497. {
  2498. giveCommand(BattleAction::WALK_AND_ATTACK, attackFromHex, activeStack->ID, myNumber);
  2499. }
  2500. };
  2501. std::string estDmgText = formatDmgRange(curInt->cb->battleEstimateDamage(sactive, shere)); //calculating estimated dmg
  2502. consoleMsg = (boost::format(CGI->generaltexth->allTexts[36]) % shere->getName() % estDmgText).str(); //Attack %s (%s damage)
  2503. }
  2504. break;
  2505. case SHOOT:
  2506. {
  2507. if(curInt->cb->battleHasShootingPenalty(activeStack, myNumber))
  2508. cursorFrame = ECursor::COMBAT_SHOOT_PENALTY;
  2509. else
  2510. cursorFrame = ECursor::COMBAT_SHOOT;
  2511. realizeAction = [=] {giveCommand(BattleAction::SHOOT, myNumber, activeStack->ID);};
  2512. std::string estDmgText = formatDmgRange(curInt->cb->battleEstimateDamage(sactive, shere)); //calculating estimated dmg
  2513. //printing - Shoot %s (%d shots left, %s damage)
  2514. consoleMsg = (boost::format(CGI->generaltexth->allTexts[296]) % shere->getName() % sactive->shots % estDmgText).str();
  2515. }
  2516. break;
  2517. case HOSTILE_CREATURE:
  2518. case FRIENDLY_CREATURE:
  2519. case RISING_SPELL:
  2520. case RANDOM_GENIE_SPELL:
  2521. if (spellToCast) //TODO: merge hero spell and creature spell into it
  2522. consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[27]) % sp->name % shere->getName()); //Cast %s on %s
  2523. else
  2524. consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[301]) % shere->getName()); //Cast a spell on %s
  2525. isCastingPossible = true;
  2526. //TODO: refactor -> include Teleport and Remove Obstacle
  2527. break;
  2528. case TELEPORT:
  2529. consoleMsg = CGI->generaltexth->allTexts[25]; //Teleport Here
  2530. isCastingPossible = true;
  2531. break;
  2532. case OBSTACLE:
  2533. consoleMsg = CGI->generaltexth->allTexts[550];
  2534. isCastingPossible = true;
  2535. break;
  2536. case OTHER_SPELL:
  2537. break;
  2538. case HEAL:
  2539. cursorFrame = ECursor::COMBAT_HEAL;
  2540. consoleMsg = (boost::format(CGI->generaltexth->allTexts[419]) % shere->getName()).str(); //Apply first aid to the %s
  2541. realizeAction = [=]{ giveCommand(BattleAction::STACK_HEAL, myNumber, activeStack->ID); }; //command healing
  2542. break;
  2543. case RISE_DEMONS:
  2544. cursorType = ECursor::SPELLBOOK;
  2545. realizeAction = [=]{ giveCommand(BattleAction::DAEMON_SUMMONING, myNumber, activeStack->ID); };
  2546. break;
  2547. case CATAPULT:
  2548. cursorFrame = ECursor::COMBAT_SHOOT_CATAPULT;
  2549. realizeAction = [=]{ giveCommand(BattleAction::CATAPULT, myNumber, activeStack->ID); };
  2550. break;
  2551. }
  2552. }
  2553. else
  2554. {
  2555. switch (illegalAction)
  2556. {
  2557. case HOSTILE_CREATURE:
  2558. case FRIENDLY_CREATURE:
  2559. case RISING_SPELL:
  2560. case RANDOM_GENIE_SPELL:
  2561. cursorFrame = ECursor::COMBAT_BLOCKED;
  2562. consoleMsg = CGI->generaltexth->allTexts[23];
  2563. break;
  2564. case TELEPORT:
  2565. consoleMsg = CGI->generaltexth->allTexts[24]; //Invalid Teleport Destination
  2566. break;
  2567. default:
  2568. cursorFrame = ECursor::COMBAT_BLOCKED;
  2569. break;
  2570. }
  2571. }
  2572. if (isCastingPossible) //common part
  2573. {
  2574. cursorType = ECursor::SPELLBOOK;
  2575. cursorFrame = 0;
  2576. if(consoleMsg.empty() && sp)
  2577. consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[26]) % sp->name); //Cast %s
  2578. realizeAction = [=]
  2579. {
  2580. if(creatureCasting)
  2581. {
  2582. giveCommand(BattleAction::MONSTER_SPELL, myNumber, sactive->ID, creatureSpellToCast);
  2583. }
  2584. else
  2585. {
  2586. spellToCast->destinationTile = myNumber;
  2587. curInt->cb->battleMakeAction(spellToCast);
  2588. endCastingSpell();
  2589. }
  2590. };
  2591. }
  2592. realizeThingsToDo();
  2593. if(noStackIsHovered)
  2594. mouseHoveredStack = -1;
  2595. if (shere && ourStack && shere->alive()) //TODO: handle hover properly
  2596. {
  2597. cursorFrame = ECursor::COMBAT_QUERY;
  2598. consoleMsg = (boost::format(CGI->generaltexth->allTexts[297]) % shere->getName()).str();
  2599. realizeAction = [=]{ GH.pushInt(createCreWindow(shere, true)); };
  2600. //setting console text
  2601. const time_t curTime = time(NULL);
  2602. CCreatureAnimation *hoveredStackAnim = creAnims[shere->ID];
  2603. if (shere->ID != mouseHoveredStack
  2604. && curTime > lastMouseHoveredStackAnimationTime + HOVER_ANIM_DELTA
  2605. && hoveredStackAnim->getType() == CCreatureAnim::HOLDING
  2606. && hoveredStackAnim->framesInGroup(CCreatureAnim::MOUSEON) > 0)
  2607. {
  2608. hoveredStackAnim->playOnce(CCreatureAnim::MOUSEON);
  2609. lastMouseHoveredStackAnimationTime = curTime;
  2610. }
  2611. noStackIsHovered = false;
  2612. mouseHoveredStack = shere->ID;
  2613. }
  2614. }
  2615. bool CBattleInterface::isCastingPossibleHere (const CStack * sactive, const CStack * shere, BattleHex myNumber)
  2616. {
  2617. creatureCasting = (spellDestSelectMode >= NO_LOCATION && spellDestSelectMode <= OTHER_SPELL) && //what does it really check?
  2618. stackCanCastSpell && shere != sactive;
  2619. //TODO: use currentAction
  2620. bool isCastingPossible = true;
  2621. int spellID = -1;
  2622. if (creatureCasting)
  2623. {
  2624. if (creatureSpellToCast > -1)
  2625. spellID = creatureSpellToCast;
  2626. }
  2627. else if(spellDestSelectMode) //hero casting
  2628. spellID = spellToCast->additionalInfo;
  2629. sp = NULL;
  2630. if (spellID >= 0)
  2631. sp = CGI->spellh->spells[spellID];
  2632. if (sp) //TODO: refactor?
  2633. {
  2634. if (creatureCasting)
  2635. isCastingPossible = (curInt->cb->battleCanCreatureCastThisSpell (sp, myNumber) == ESpellCastProblem::OK);
  2636. else
  2637. isCastingPossible = (curInt->cb->battleCanCastThisSpell (sp, myNumber) == ESpellCastProblem::OK);
  2638. }
  2639. if(!myNumber.isAvailable() && !shere) //empty tile outside battlefield (or in the unavailable border column)
  2640. isCastingPossible = false;
  2641. return isCastingPossible;
  2642. }
  2643. BattleHex CBattleInterface::fromWhichHexAttack(BattleHex myNumber)
  2644. {
  2645. //TODO far too much repeating code
  2646. BattleHex destHex = -1;
  2647. switch(CCS->curh->number)
  2648. {
  2649. case 12: //from bottom right
  2650. {
  2651. bool doubleWide = activeStack->doubleWide();
  2652. destHex = myNumber + ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH : GameConstants::BFIELD_WIDTH+1 ) +
  2653. (activeStack->attackerOwned && doubleWide ? 1 : 0);
  2654. if(vstd::contains(occupyableHexes, destHex))
  2655. return destHex;
  2656. else if(activeStack->attackerOwned) //if we are attacker
  2657. {
  2658. if(vstd::contains(occupyableHexes, destHex+1))
  2659. return destHex+1;
  2660. }
  2661. else //if we are defender
  2662. {
  2663. if(vstd::contains(occupyableHexes, destHex-1))
  2664. return destHex-1;
  2665. }
  2666. break;
  2667. }
  2668. case 7: //from bottom left
  2669. {
  2670. destHex = myNumber + ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH-1 : GameConstants::BFIELD_WIDTH );
  2671. if(vstd::contains(occupyableHexes, destHex))
  2672. return destHex;
  2673. else if(activeStack->attackerOwned) //if we are attacker
  2674. {
  2675. if(vstd::contains(occupyableHexes, destHex+1))
  2676. return destHex+1;
  2677. }
  2678. else //if we are defender
  2679. {
  2680. if(vstd::contains(occupyableHexes, destHex-1))
  2681. return destHex-1;
  2682. }
  2683. break;
  2684. }
  2685. case 8: //from left
  2686. {
  2687. if(activeStack->doubleWide() && !activeStack->attackerOwned)
  2688. {
  2689. std::vector<BattleHex> acc = curInt->cb->battleGetAvailableHexes(activeStack, false);
  2690. if(vstd::contains(acc, myNumber))
  2691. return myNumber - 1;
  2692. else
  2693. return myNumber - 2;
  2694. }
  2695. else
  2696. {
  2697. return myNumber - 1;
  2698. }
  2699. break;
  2700. }
  2701. case 9: //from top left
  2702. {
  2703. destHex = myNumber - ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH+1 : GameConstants::BFIELD_WIDTH );
  2704. if(vstd::contains(occupyableHexes, destHex))
  2705. return destHex;
  2706. else if(activeStack->attackerOwned) //if we are attacker
  2707. {
  2708. if(vstd::contains(occupyableHexes, destHex+1))
  2709. return destHex+1;
  2710. }
  2711. else //if we are defender
  2712. {
  2713. if(vstd::contains(occupyableHexes, destHex-1))
  2714. return destHex-1;
  2715. }
  2716. break;
  2717. }
  2718. case 10: //from top right
  2719. {
  2720. bool doubleWide = activeStack->doubleWide();
  2721. destHex = myNumber - ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH : GameConstants::BFIELD_WIDTH-1 ) +
  2722. (activeStack->attackerOwned && doubleWide ? 1 : 0);
  2723. if(vstd::contains(occupyableHexes, destHex))
  2724. return destHex;
  2725. else if(activeStack->attackerOwned) //if we are attacker
  2726. {
  2727. if(vstd::contains(occupyableHexes, destHex+1))
  2728. return destHex+1;
  2729. }
  2730. else //if we are defender
  2731. {
  2732. if(vstd::contains(occupyableHexes, destHex-1))
  2733. return destHex-1;
  2734. }
  2735. break;
  2736. }
  2737. case 11: //from right
  2738. {
  2739. if(activeStack->doubleWide() && activeStack->attackerOwned)
  2740. {
  2741. std::vector<BattleHex> acc = curInt->cb->battleGetAvailableHexes(activeStack, false);
  2742. if(vstd::contains(acc, myNumber))
  2743. return myNumber + 1;
  2744. else
  2745. return myNumber + 2;
  2746. }
  2747. else
  2748. {
  2749. return myNumber + 1;
  2750. }
  2751. break;
  2752. }
  2753. case 13: //from bottom
  2754. {
  2755. destHex = myNumber + ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH : GameConstants::BFIELD_WIDTH+1 );
  2756. if(vstd::contains(occupyableHexes, destHex))
  2757. return destHex;
  2758. else if(attackingHeroInstance->tempOwner == curInt->cb->getMyColor()) //if we are attacker
  2759. {
  2760. if(vstd::contains(occupyableHexes, destHex+1))
  2761. return destHex+1;
  2762. }
  2763. else //if we are defender
  2764. {
  2765. if(vstd::contains(occupyableHexes, destHex-1))
  2766. return destHex-1;
  2767. }
  2768. break;
  2769. }
  2770. case 14: //from top
  2771. {
  2772. destHex = myNumber - ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH : GameConstants::BFIELD_WIDTH-1 );
  2773. if(vstd::contains(occupyableHexes, destHex))
  2774. return destHex;
  2775. else if(attackingHeroInstance->tempOwner == curInt->cb->getMyColor()) //if we are attacker
  2776. {
  2777. if(vstd::contains(occupyableHexes, destHex+1))
  2778. return destHex+1;
  2779. }
  2780. else //if we are defender
  2781. {
  2782. if(vstd::contains(occupyableHexes, destHex-1))
  2783. return destHex-1;
  2784. }
  2785. break;
  2786. }
  2787. }
  2788. return -1;
  2789. }
  2790. std::string CBattleInterface::SiegeHelper::townTypeInfixes[GameConstants::F_NUMBER] = {"CS", "RM", "TW", "IN", "NC", "DN", "ST", "FR", "EL"};
  2791. CBattleInterface::SiegeHelper::SiegeHelper(const CGTownInstance *siegeTown, const CBattleInterface * _owner)
  2792. : owner(_owner), town(siegeTown)
  2793. {
  2794. for(int g = 0; g < ARRAY_COUNT(walls); ++g)
  2795. {
  2796. walls[g] = BitmapHandler::loadBitmap( getSiegeName(g) );
  2797. }
  2798. }
  2799. CBattleInterface::SiegeHelper::~SiegeHelper()
  2800. {
  2801. for(int g = 0; g < ARRAY_COUNT(walls); ++g)
  2802. {
  2803. SDL_FreeSurface(walls[g]);
  2804. }
  2805. }
  2806. std::string CBattleInterface::SiegeHelper::getSiegeName(ui16 what, ui16 additInfo) const
  2807. {
  2808. if(what == 2 || what == 3 || what == 8)
  2809. {
  2810. if(additInfo == 3) additInfo = 2;
  2811. }
  2812. char buf[100];
  2813. SDL_itoa(additInfo, buf, 10);
  2814. std::string addit(buf);
  2815. switch(what)
  2816. {
  2817. case 0: //background
  2818. return "SG" + townTypeInfixes[town->town->typeID] + "BACK.BMP";
  2819. case 1: //background wall
  2820. {
  2821. switch(town->town->typeID)
  2822. {
  2823. case 5: case 4: case 1: case 6:
  2824. return "SG" + townTypeInfixes[town->town->typeID] + "TPW1.BMP";
  2825. case 0: case 2: case 3: case 7: case 8:
  2826. return "SG" + townTypeInfixes[town->town->typeID] + "TPWL.BMP";
  2827. default:
  2828. return "";
  2829. }
  2830. }
  2831. case 2: //keep
  2832. return "SG" + townTypeInfixes[town->town->typeID] + "MAN" + addit + ".BMP";
  2833. case 3: //bottom tower
  2834. return "SG" + townTypeInfixes[town->town->typeID] + "TW1" + addit + ".BMP";
  2835. case 4: //bottom wall
  2836. return "SG" + townTypeInfixes[town->town->typeID] + "WA1" + addit + ".BMP";
  2837. case 5: //below gate
  2838. return "SG" + townTypeInfixes[town->town->typeID] + "WA3" + addit + ".BMP";
  2839. case 6: //over gate
  2840. return "SG" + townTypeInfixes[town->town->typeID] + "WA4" + addit + ".BMP";
  2841. case 7: //upper wall
  2842. return "SG" + townTypeInfixes[town->town->typeID] + "WA6" + addit + ".BMP";
  2843. case 8: //upper tower
  2844. return "SG" + townTypeInfixes[town->town->typeID] + "TW2" + addit + ".BMP";
  2845. case 9: //gate
  2846. return "SG" + townTypeInfixes[town->town->typeID] + "DRW" + addit + ".BMP";
  2847. case 10: //gate arch
  2848. return "SG" + townTypeInfixes[town->town->typeID] + "ARCH.BMP";
  2849. case 11: //bottom static wall
  2850. return "SG" + townTypeInfixes[town->town->typeID] + "WA2.BMP";
  2851. case 12: //upper static wall
  2852. return "SG" + townTypeInfixes[town->town->typeID] + "WA5.BMP";
  2853. case 13: //moat
  2854. return "SG" + townTypeInfixes[town->town->typeID] + "MOAT.BMP";
  2855. case 14: //mlip
  2856. return "SG" + townTypeInfixes[town->town->typeID] + "MLIP.BMP";
  2857. case 15: //keep creature cover
  2858. return "SG" + townTypeInfixes[town->town->typeID] + "MANC.BMP";
  2859. case 16: //bottom turret creature cover
  2860. return "SG" + townTypeInfixes[town->town->typeID] + "TW1C.BMP";
  2861. case 17: //upper turret creature cover
  2862. return "SG" + townTypeInfixes[town->town->typeID] + "TW2C.BMP";
  2863. default:
  2864. return "";
  2865. }
  2866. }
  2867. /// What: 1. background wall, 2. keep, 3. bottom tower, 4. bottom wall, 5. wall below gate,
  2868. /// 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,
  2869. /// 15. keep turret cover, 16. lower turret cover, 17. upper turret cover
  2870. /// Positions are loaded from the config file: /config/wall_pos.txt
  2871. void CBattleInterface::SiegeHelper::printPartOfWall(SDL_Surface * to, int what)
  2872. {
  2873. Point pos = Point(-1, -1);
  2874. if (what >= 1 && what <= 17)
  2875. {
  2876. pos.x = graphics->wallPositions[town->town->typeID][what - 1].x + owner->pos.x;
  2877. pos.y = graphics->wallPositions[town->town->typeID][what - 1].y + owner->pos.y;
  2878. }
  2879. if(pos.x != -1)
  2880. {
  2881. blitAt(walls[what], pos.x, pos.y, to);
  2882. }
  2883. }
  2884. double CatapultProjectileInfo::calculateY(double x)
  2885. {
  2886. return (facA * pow(10., -3.)) * pow(x, 2.0) + facB * x + facC;
  2887. }