CBattleInterface.cpp 98 KB

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