CBattleInterface.cpp 113 KB

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