CBattleInterface.cpp 102 KB

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