CBattleInterface.cpp 116 KB

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