CBattleInterface.cpp 128 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389
  1. #include "CBattleInterface.h"
  2. #include "CGameInfo.h"
  3. #include "../lib/CLodHandler.h"
  4. #include "SDL_Extensions.h"
  5. #include "CAdvmapInterface.h"
  6. #include "AdventureMapButton.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 "CCursorHandler.h"
  15. #include "../CCallback.h"
  16. #include "../lib/BattleState.h"
  17. #include "../lib/CGeneralTextHandler.h"
  18. #include "CCreatureAnimation.h"
  19. #include "Graphics.h"
  20. #include "CSpellWindow.h"
  21. #include "CConfigHandler.h"
  22. #include <queue>
  23. #include <sstream>
  24. #include "../lib/CondSh.h"
  25. #include "../lib/NetPacks.h"
  26. #include "CPlayerInterface.h"
  27. #include "CVideoHandler.h"
  28. #include "../lib/CTownHandler.h"
  29. #include <boost/assign/list_of.hpp>
  30. #include <boost/foreach.hpp>
  31. #include <boost/lexical_cast.hpp>
  32. #include <boost/algorithm/string/replace.hpp>
  33. #ifndef __GNUC__
  34. const double M_PI = 3.14159265358979323846;
  35. #else
  36. #define _USE_MATH_DEFINES
  37. #include <cmath>
  38. #endif
  39. /*
  40. * CBattleInterface.cpp, part of VCMI engine
  41. *
  42. * Authors: listed in file AUTHORS in main folder
  43. *
  44. * License: GNU General Public License v2.0 or later
  45. * Full text of license available in license.txt file, in main folder
  46. *
  47. */
  48. extern SDL_Surface * screen;
  49. extern SDL_Color zwykly;
  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, float rCor, float gCor, float 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 = (float)((colorsToChange+g)->r) * rCor;
  68. (colorsToChange+g)->g = (float)((colorsToChange+g)->g) * gCor;
  69. (colorsToChange+g)->b = (float)((colorsToChange+g)->b) * bCor;
  70. }
  71. }
  72. }
  73. ////////////////////////Battle helpers
  74. //general anim
  75. void CBattleAnimation::endAnim()
  76. {
  77. for(std::list<std::pair<CBattleAnimation *, bool> >::iterator it = owner->pendingAnims.begin(); it != owner->pendingAnims.end(); ++it)
  78. {
  79. if(it->first == this)
  80. {
  81. it->first = NULL;
  82. }
  83. }
  84. }
  85. bool CBattleAnimation::isEarliest(bool perStackConcurrency)
  86. {
  87. int lowestMoveID = owner->animIDhelper + 5;
  88. CBattleStackAnimation * thAnim = dynamic_cast<CBattleStackAnimation *>(this);
  89. CSpellEffectAnim * thSen = dynamic_cast<CSpellEffectAnim *>(this);
  90. for(std::list<std::pair<CBattleAnimation *, bool> >::iterator it = owner->pendingAnims.begin(); it != owner->pendingAnims.end(); ++it)
  91. {
  92. CBattleStackAnimation * stAnim = dynamic_cast<CBattleStackAnimation *>(it->first);
  93. CSpellEffectAnim * sen = dynamic_cast<CSpellEffectAnim *>(it->first);
  94. if(perStackConcurrency && stAnim && thAnim && stAnim->stack->ID != thAnim->stack->ID)
  95. continue;
  96. if(sen && thSen && sen != thSen && perStackConcurrency)
  97. continue;
  98. CReverseAnim * revAnim = dynamic_cast<CReverseAnim *>(stAnim);
  99. if(revAnim && thAnim && stAnim && stAnim->stack->ID == thAnim->stack->ID && revAnim->priority)
  100. return false;
  101. if(it->first)
  102. amin(lowestMoveID, it->first->ID);
  103. }
  104. return ID == lowestMoveID || lowestMoveID == (owner->animIDhelper + 5);
  105. }
  106. CBattleAnimation::CBattleAnimation(CBattleInterface * _owner)
  107. : owner(_owner), ID(_owner->animIDhelper++)
  108. {}
  109. //Dummy animation
  110. bool CDummyAnim::init()
  111. {
  112. return true;
  113. }
  114. void CDummyAnim::nextFrame()
  115. {
  116. counter++;
  117. if(counter > howMany)
  118. endAnim();
  119. }
  120. void CDummyAnim::endAnim()
  121. {
  122. CBattleAnimation::endAnim();
  123. delete this;
  124. }
  125. CDummyAnim::CDummyAnim(CBattleInterface * _owner, int howManyFrames) : CBattleAnimation(_owner), counter(0), howMany(howManyFrames)
  126. {
  127. }
  128. //effect animation
  129. bool CSpellEffectAnim::init()
  130. {
  131. if(!isEarliest(true))
  132. return false;
  133. if(effect == 12) //armageddon
  134. {
  135. if(effect == -1 || graphics->battleACToDef[effect].size() != 0)
  136. {
  137. CDefHandler * anim;
  138. if(customAnim.size())
  139. anim = CDefHandler::giveDef(customAnim);
  140. else
  141. anim = CDefHandler::giveDef(graphics->battleACToDef[effect][0]);
  142. if (Vflip)
  143. {
  144. for (int v=0; v<anim->ourImages.size(); ++v)
  145. {
  146. CSDL_Ext::VflipSurf(anim->ourImages[v].bitmap);
  147. }
  148. }
  149. for(int i=0; i * anim->width < owner->pos.w ; ++i)
  150. {
  151. for(int j=0; j * anim->height < owner->pos.h ; ++j)
  152. {
  153. SBattleEffect be;
  154. be.effectID = ID;
  155. be.anim = CDefHandler::giveDef(graphics->battleACToDef[effect][0]);
  156. if (Vflip)
  157. {
  158. for (int v=0; v<be.anim->ourImages.size(); ++v)
  159. {
  160. CSDL_Ext::VflipSurf(be.anim->ourImages[v].bitmap);
  161. }
  162. }
  163. be.frame = 0;
  164. be.maxFrame = be.anim->ourImages.size();
  165. be.x = i * anim->width + owner->pos.x;
  166. be.y = j * anim->height + owner->pos.y;
  167. owner->battleEffects.push_back(be);
  168. }
  169. }
  170. }
  171. else //there is nothing to play
  172. {
  173. endAnim();
  174. return false;
  175. }
  176. }
  177. else // Effects targeted at a specific creature/hex.
  178. {
  179. if(effect == -1 || graphics->battleACToDef[effect].size() != 0)
  180. {
  181. const CStack* destStack = owner->curInt->cb->battleGetStackByPos(destTile, false);
  182. Rect &tilePos = owner->bfield[destTile].pos;
  183. SBattleEffect be;
  184. be.effectID = ID;
  185. if(customAnim.size())
  186. be.anim = CDefHandler::giveDef(customAnim);
  187. else
  188. be.anim = CDefHandler::giveDef(graphics->battleACToDef[effect][0]);
  189. if (Vflip)
  190. {
  191. for (int v=0; v<be.anim->ourImages.size(); ++v)
  192. {
  193. CSDL_Ext::VflipSurf(be.anim->ourImages[v].bitmap);
  194. }
  195. }
  196. be.frame = 0;
  197. be.maxFrame = be.anim->ourImages.size();
  198. if(effect == 1)
  199. be.maxFrame = 3;
  200. switch (effect)
  201. {
  202. case -1:
  203. be.x = x;
  204. be.y = y;
  205. break;
  206. case 0: // Prayer and Lightning Bolt.
  207. case 1:
  208. // Position effect with it's bottom center touching the bottom center of affected tile(s).
  209. be.x = tilePos.x + tilePos.w/2 - be.anim->width/2;
  210. be.y = tilePos.y + tilePos.h - be.anim->height;
  211. break;
  212. default:
  213. // Position effect with it's center touching the top center of affected tile(s).
  214. be.x = tilePos.x + tilePos.w/2 - be.anim->width/2;
  215. be.y = tilePos.y - be.anim->height/2;
  216. break;
  217. }
  218. // Correction for 2-hex creatures.
  219. if (destStack != NULL && destStack->doubleWide())
  220. be.x += (destStack->attackerOwned ? -1 : 1)*tilePos.w/2;
  221. owner->battleEffects.push_back(be);
  222. }
  223. else //there is nothing to play
  224. {
  225. endAnim();
  226. return false;
  227. }
  228. }
  229. //battleEffects
  230. return true;
  231. }
  232. void CSpellEffectAnim::nextFrame()
  233. {
  234. //notice: there may be more than one effect in owner->battleEffects correcponding to this animation (ie. armageddon)
  235. for(std::list<SBattleEffect>::iterator it = owner->battleEffects.begin(); it != owner->battleEffects.end(); ++it)
  236. {
  237. if(it->effectID == ID)
  238. {
  239. ++(it->frame);
  240. if(it->frame == it->maxFrame)
  241. {
  242. endAnim();
  243. break;
  244. }
  245. else
  246. {
  247. it->x += dx;
  248. it->y += dy;
  249. }
  250. }
  251. }
  252. }
  253. void CSpellEffectAnim::endAnim()
  254. {
  255. CBattleAnimation::endAnim();
  256. std::vector<std::list<SBattleEffect>::iterator> toDel;
  257. for(std::list<SBattleEffect>::iterator it = owner->battleEffects.begin(); it != owner->battleEffects.end(); ++it)
  258. {
  259. if(it->effectID == ID)
  260. {
  261. toDel.push_back(it);
  262. }
  263. }
  264. for(int b=0; b<toDel.size(); ++b)
  265. {
  266. delete toDel[b]->anim;
  267. owner->battleEffects.erase(toDel[b]);
  268. }
  269. delete this;
  270. }
  271. CSpellEffectAnim::CSpellEffectAnim(CBattleInterface * _owner, ui32 _effect, THex _destTile, int _dx, int _dy, bool _Vflip)
  272. :CBattleAnimation(_owner), effect(_effect), destTile(_destTile), customAnim(""), dx(_dx), dy(_dy), Vflip(_Vflip)
  273. {
  274. }
  275. CSpellEffectAnim::CSpellEffectAnim(CBattleInterface * _owner, std::string _customAnim, int _x, int _y, int _dx, int _dy, bool _Vflip)
  276. :CBattleAnimation(_owner), effect(-1), destTile(0), customAnim(_customAnim), x(_x), y(_y), dx(_dx), dy(_dy), Vflip(_Vflip)
  277. {
  278. }
  279. //stack's aniamtion
  280. CBattleStackAnimation::CBattleStackAnimation(CBattleInterface * _owner, const CStack * _stack)
  281. : CBattleAnimation(_owner), stack(_stack)
  282. {
  283. }
  284. bool CBattleStackAnimation::isToReverseHlp(THex hexFrom, THex hexTo, bool curDir)
  285. {
  286. int fromMod = hexFrom % BFIELD_WIDTH;
  287. int fromDiv = hexFrom / BFIELD_WIDTH;
  288. int toMod = hexTo % BFIELD_WIDTH;
  289. if(curDir && fromMod < toMod)
  290. return false;
  291. else if(curDir && fromMod > toMod)
  292. return true;
  293. else if(curDir && fromMod == toMod)
  294. {
  295. return fromDiv % 2 == 0;
  296. }
  297. else if(!curDir && fromMod < toMod)
  298. return true;
  299. else if(!curDir && fromMod > toMod)
  300. return false;
  301. else if(!curDir && fromMod == toMod)
  302. {
  303. return fromDiv % 2 == 1;
  304. }
  305. tlog1 << "Catastrope in CBattleStackAnimation::isToReverse!" << std::endl;
  306. return false; //should never happen
  307. }
  308. bool CBattleStackAnimation::isToReverse(THex hexFrom, THex hexTo, bool curDir, bool toDoubleWide, bool toDir)
  309. {
  310. if(hexTo < 0) //turret
  311. return false;
  312. if(toDoubleWide)
  313. {
  314. return isToReverseHlp(hexFrom, hexTo, curDir) &&
  315. (toDir ? isToReverseHlp(hexFrom, hexTo-1, curDir) : isToReverseHlp(hexFrom, hexTo+1, curDir) );
  316. }
  317. else
  318. {
  319. return isToReverseHlp(hexFrom, hexTo, curDir);
  320. }
  321. }
  322. //revering animation
  323. bool CReverseAnim::init()
  324. {
  325. if(owner->creAnims[stack->ID] == NULL || owner->creAnims[stack->ID]->getType() == 5)
  326. {
  327. endAnim();
  328. return false; //there is no such creature
  329. }
  330. if(!priority && !isEarliest(false))
  331. return false;
  332. owner->creAnims[stack->ID]->setType(CCreatureAnim::TURN_R);
  333. return true;
  334. }
  335. void CReverseAnim::nextFrame()
  336. {
  337. if(partOfAnim == 1) //first part of animation
  338. {
  339. if(owner->creAnims[stack->ID]->onLastFrameInGroup())
  340. {
  341. partOfAnim = 2;
  342. }
  343. }
  344. else if(partOfAnim == 2)
  345. {
  346. if(!secondPartSetup)
  347. {
  348. owner->creDir[stack->ID] = !owner->creDir[stack->ID];
  349. if(!stack)
  350. {
  351. endAnim();
  352. return;
  353. }
  354. Point coords = CBattleHex::getXYUnitAnim(hex, owner->creDir[stack->ID], stack, owner);
  355. owner->creAnims[stack->ID]->pos.x = coords.x;
  356. //creAnims[stackID]->pos.y = coords.second;
  357. if(stack->doubleWide())
  358. {
  359. if(stack->attackerOwned)
  360. {
  361. if(!owner->creDir[stack->ID])
  362. owner->creAnims[stack->ID]->pos.x -= 44;
  363. }
  364. else
  365. {
  366. if(owner->creDir[stack->ID])
  367. owner->creAnims[stack->ID]->pos.x += 44;
  368. }
  369. }
  370. owner->creAnims[stack->ID]->setType(CCreatureAnim::TURN_L);
  371. secondPartSetup = true;
  372. }
  373. if(owner->creAnims[stack->ID]->onLastFrameInGroup())
  374. {
  375. endAnim();
  376. }
  377. }
  378. }
  379. void CReverseAnim::endAnim()
  380. {
  381. CBattleAnimation::endAnim();
  382. if( stack->alive() )//don't do that if stack is dead
  383. owner->creAnims[stack->ID]->setType(CCreatureAnim::HOLDING);
  384. delete this;
  385. }
  386. CReverseAnim::CReverseAnim(CBattleInterface * _owner, const CStack * stack, THex dest, bool _priority)
  387. : CBattleStackAnimation(_owner, stack), partOfAnim(1), secondPartSetup(false), hex(dest), priority(_priority)
  388. {
  389. }
  390. //defence anim
  391. bool CDefenceAnim::init()
  392. {
  393. //checking initial conditions
  394. //if(owner->creAnims[stackID]->getType() != 2)
  395. //{
  396. // return false;
  397. //}
  398. if(attacker == NULL && owner->battleEffects.size() > 0)
  399. return false;
  400. int lowestMoveID = owner->animIDhelper + 5;
  401. for(std::list<std::pair<CBattleAnimation *, bool> >::iterator it = owner->pendingAnims.begin(); it != owner->pendingAnims.end(); ++it)
  402. {
  403. CDefenceAnim * defAnim = dynamic_cast<CDefenceAnim *>(it->first);
  404. if(defAnim && defAnim->stack->ID != stack->ID)
  405. continue;
  406. CBattleAttack * attAnim = dynamic_cast<CBattleAttack *>(it->first);
  407. if(attAnim && attAnim->stack->ID != stack->ID)
  408. continue;
  409. if(attacker != NULL)
  410. {
  411. int attackerAnimType = owner->creAnims[attacker->ID]->getType();
  412. if( attackerAnimType == 11 && attackerAnimType == 12 && attackerAnimType == 13 && owner->creAnims[attacker->ID]->getFrame() < attacker->getCreature()->attackClimaxFrame )
  413. return false;
  414. }
  415. CReverseAnim * animAsRev = dynamic_cast<CReverseAnim *>(it->first);
  416. if(animAsRev && animAsRev->priority)
  417. return false;
  418. if(it->first)
  419. amin(lowestMoveID, it->first->ID);
  420. }
  421. if(ID > lowestMoveID)
  422. return false;
  423. //reverse unit if necessary
  424. if(attacker && isToReverse(stack->position, attacker->position, owner->creDir[stack->ID], attacker->doubleWide(), owner->creDir[attacker->ID]))
  425. {
  426. owner->addNewAnim(new CReverseAnim(owner, stack, stack->position, true));
  427. return false;
  428. }
  429. //unit reversed
  430. if(byShooting) //delay hit animation
  431. {
  432. for(std::list<SProjectileInfo>::const_iterator it = owner->projectiles.begin(); it != owner->projectiles.end(); ++it)
  433. {
  434. if(it->creID == attacker->getCreature()->idNumber)
  435. {
  436. return false;
  437. }
  438. }
  439. }
  440. //initializing
  441. if(killed)
  442. {
  443. CCS->soundh->playSound(battle_sound(stack->getCreature(), killed));
  444. owner->creAnims[stack->ID]->setType(CCreatureAnim::DEATH); //death
  445. }
  446. else
  447. {
  448. // TODO: this block doesn't seems correct if the unit is defending.
  449. CCS->soundh->playSound(battle_sound(stack->getCreature(), wince));
  450. owner->creAnims[stack->ID]->setType(CCreatureAnim::HITTED); //getting hit
  451. }
  452. return true; //initialized successfuly
  453. }
  454. void CDefenceAnim::nextFrame()
  455. {
  456. if(!killed && owner->creAnims[stack->ID]->getType() != CCreatureAnim::HITTED)
  457. {
  458. owner->creAnims[stack->ID]->setType(CCreatureAnim::HITTED);
  459. }
  460. if(!owner->creAnims[stack->ID]->onLastFrameInGroup())
  461. {
  462. if( owner->creAnims[stack->ID]->getType() == CCreatureAnim::DEATH && (owner->animCount+1)%(4/owner->curInt->sysOpts.animSpeed)==0
  463. && !owner->creAnims[stack->ID]->onLastFrameInGroup() )
  464. {
  465. owner->creAnims[stack->ID]->incrementFrame();
  466. }
  467. }
  468. else
  469. {
  470. endAnim();
  471. }
  472. }
  473. void CDefenceAnim::endAnim()
  474. {
  475. //restoring animType
  476. if(owner->creAnims[stack->ID]->getType() == CCreatureAnim::HITTED)
  477. owner->creAnims[stack->ID]->setType(CCreatureAnim::HOLDING);
  478. //printing info to console
  479. if(attacker!=NULL)
  480. owner->printConsoleAttacked(stack, dmg, amountKilled, attacker);
  481. //const CStack * attacker = owner->curInt->cb->battleGetStackByID(IDby, false);
  482. //const CStack * attacked = owner->curInt->cb->battleGetStackByID(stackID, false);
  483. CBattleAnimation::endAnim();
  484. delete this;
  485. }
  486. CDefenceAnim::CDefenceAnim(SStackAttackedInfo _attackedInfo, CBattleInterface * _owner)
  487. : CBattleStackAnimation(_owner, _attackedInfo.defender), dmg(_attackedInfo.dmg),
  488. amountKilled(_attackedInfo.amountKilled), attacker(_attackedInfo.attacker), byShooting(_attackedInfo.byShooting),
  489. killed(_attackedInfo.killed)
  490. {
  491. }
  492. ////move anim
  493. bool CBattleStackMoved::init()
  494. {
  495. if( !isEarliest(false) )
  496. return false;
  497. //a few useful variables
  498. steps = owner->creAnims[stack->ID]->framesInGroup(CCreatureAnim::MOVING)*owner->getAnimSpeedMultiplier()-1;
  499. if(steps == 0) //this creature seems to have no move animation so we can end it immediately
  500. {
  501. endAnim();
  502. return false;
  503. }
  504. whichStep = 0;
  505. int hexWbase = 44, hexHbase = 42;
  506. const CStack * movedStack = stack;
  507. if(!movedStack || owner->creAnims[stack->ID]->getType() == 5)
  508. {
  509. endAnim();
  510. return false;
  511. }
  512. //bool twoTiles = movedStack->doubleWide();
  513. Point begPosition = CBattleHex::getXYUnitAnim(curStackPos, movedStack->attackerOwned, movedStack, owner);
  514. Point endPosition = CBattleHex::getXYUnitAnim(destHex, movedStack->attackerOwned, movedStack, owner);
  515. int mutPos = THex::mutualPosition(curStackPos, destHex);
  516. //reverse unit if necessary
  517. if((begPosition.x > endPosition.x) && owner->creDir[stack->ID] == true)
  518. {
  519. owner->addNewAnim(new CReverseAnim(owner, stack, curStackPos, true));
  520. return false;
  521. }
  522. else if ((begPosition.x < endPosition.x) && owner->creDir[stack->ID] == false)
  523. {
  524. owner->addNewAnim(new CReverseAnim(owner, stack, curStackPos, true));
  525. return false;
  526. }
  527. if(owner->creAnims[stack->ID]->getType() != CCreatureAnim::MOVING)
  528. {
  529. owner->creAnims[stack->ID]->setType(CCreatureAnim::MOVING);
  530. }
  531. //unit reversed
  532. if(owner->moveSh <= 0)
  533. owner->moveSh = CCS->soundh->playSound(battle_sound(movedStack->getCreature(), move), -1);
  534. //step shift calculation
  535. posX = owner->creAnims[stack->ID]->pos.x, posY = owner->creAnims[stack->ID]->pos.y; // for precise calculations ;]
  536. if(mutPos == -1 && movedStack->hasBonusOfType(Bonus::FLYING))
  537. {
  538. steps *= distance;
  539. steps /= 2; //to make animation faster
  540. stepX = (endPosition.x - (float)begPosition.x)/steps;
  541. stepY = (endPosition.y - (float)begPosition.y)/steps;
  542. }
  543. else
  544. {
  545. switch(mutPos)
  546. {
  547. case 0:
  548. stepX = (-1.0)*((float)hexWbase)/(2.0f*steps);
  549. stepY = (-1.0)*((float)hexHbase)/((float)steps);
  550. break;
  551. case 1:
  552. stepX = ((float)hexWbase)/(2.0f*steps);
  553. stepY = (-1.0)*((float)hexHbase)/((float)steps);
  554. break;
  555. case 2:
  556. stepX = ((float)hexWbase)/((float)steps);
  557. stepY = 0.0;
  558. break;
  559. case 3:
  560. stepX = ((float)hexWbase)/(2.0f*steps);
  561. stepY = ((float)hexHbase)/((float)steps);
  562. break;
  563. case 4:
  564. stepX = (-1.0)*((float)hexWbase)/(2.0f*steps);
  565. stepY = ((float)hexHbase)/((float)steps);
  566. break;
  567. case 5:
  568. stepX = (-1.0)*((float)hexWbase)/((float)steps);
  569. stepY = 0.0;
  570. break;
  571. }
  572. }
  573. //step shifts calculated
  574. return true;
  575. }
  576. void CBattleStackMoved::nextFrame()
  577. {
  578. //moving instructions
  579. posX += stepX;
  580. owner->creAnims[stack->ID]->pos.x = posX;
  581. posY += stepY;
  582. owner->creAnims[stack->ID]->pos.y = posY;
  583. ++whichStep;
  584. if(whichStep == steps)
  585. {
  586. endAnim();
  587. }
  588. }
  589. void CBattleStackMoved::endAnim()
  590. {
  591. const CStack * movedStack = stack;
  592. CBattleAnimation::endAnim();
  593. if(movedStack)
  594. {
  595. bool twoTiles = movedStack->doubleWide();
  596. if(endMoving)
  597. {
  598. owner->addNewAnim(new CBattleMoveEnd(owner, stack, destHex));
  599. }
  600. Point coords = CBattleHex::getXYUnitAnim(destHex, owner->creDir[stack->ID], movedStack, owner);
  601. owner->creAnims[stack->ID]->pos = coords;
  602. if(!endMoving && twoTiles && bool(movedStack->attackerOwned) && (owner->creDir[stack->ID] != bool(movedStack->attackerOwned) )) //big attacker creature is reversed
  603. owner->creAnims[stack->ID]->pos.x -= 44;
  604. else if(!endMoving && twoTiles && (! bool(movedStack->attackerOwned) ) && (owner->creDir[stack->ID] != bool(movedStack->attackerOwned) )) //big defender creature is reversed
  605. owner->creAnims[stack->ID]->pos.x += 44;
  606. }
  607. if(owner->moveSh >= 0)
  608. {
  609. CCS->soundh->stopSound(owner->moveSh);
  610. owner->moveSh = -1;
  611. }
  612. delete this;
  613. }
  614. CBattleStackMoved::CBattleStackMoved(CBattleInterface * _owner, const CStack * _stack, THex _destHex, bool _endMoving, int _distance)
  615. : CBattleStackAnimation(_owner, _stack), destHex(_destHex), endMoving(_endMoving), distance(_distance), stepX(0.0f), stepY(0.0f)
  616. {
  617. curStackPos = stack->position;
  618. }
  619. //move started
  620. bool CBattleMoveStart::init()
  621. {
  622. if( !isEarliest(false) )
  623. return false;
  624. if(!stack || owner->creAnims[stack->ID]->getType() == 5)
  625. {
  626. CBattleMoveStart::endAnim();
  627. return false;
  628. }
  629. CCS->soundh->playSound(battle_sound(stack->getCreature(), startMoving));
  630. owner->creAnims[stack->ID]->setType(CCreatureAnim::MOVE_START);
  631. return true;
  632. }
  633. void CBattleMoveStart::nextFrame()
  634. {
  635. if(owner->creAnims[stack->ID]->onLastFrameInGroup())
  636. {
  637. endAnim();
  638. }
  639. else
  640. {
  641. if((owner->animCount+1)%(4/owner->curInt->sysOpts.animSpeed)==0)
  642. owner->creAnims[stack->ID]->incrementFrame();
  643. }
  644. }
  645. void CBattleMoveStart::endAnim()
  646. {
  647. CBattleAnimation::endAnim();
  648. delete this;
  649. }
  650. CBattleMoveStart::CBattleMoveStart(CBattleInterface * _owner, const CStack * _stack)
  651. : CBattleStackAnimation(_owner, _stack)
  652. {
  653. }
  654. //move finished
  655. bool CBattleMoveEnd::init()
  656. {
  657. if( !isEarliest(true) )
  658. return false;
  659. if(!stack || owner->creAnims[stack->ID]->framesInGroup(CCreatureAnim::MOVE_END) == 0 ||
  660. owner->creAnims[stack->ID]->getType() == CCreatureAnim::DEATH)
  661. {
  662. endAnim();
  663. return false;
  664. }
  665. CCS->soundh->playSound(battle_sound(stack->getCreature(), endMoving));
  666. owner->creAnims[stack->ID]->setType(CCreatureAnim::MOVE_END);
  667. return true;
  668. }
  669. void CBattleMoveEnd::nextFrame()
  670. {
  671. if(owner->creAnims[stack->ID]->onLastFrameInGroup())
  672. {
  673. endAnim();
  674. }
  675. }
  676. void CBattleMoveEnd::endAnim()
  677. {
  678. CBattleAnimation::endAnim();
  679. if(owner->creAnims[stack->ID]->getType() != CCreatureAnim::DEATH)
  680. owner->creAnims[stack->ID]->setType(CCreatureAnim::HOLDING); //resetting to default
  681. CCS->curh->show();
  682. delete this;
  683. }
  684. CBattleMoveEnd::CBattleMoveEnd(CBattleInterface * _owner, const CStack * _stack, THex destTile)
  685. : CBattleStackAnimation(_owner, _stack), destinationTile(destTile)
  686. {
  687. }
  688. //general attack anim
  689. void CBattleAttack::nextFrame()
  690. {
  691. if(owner->creAnims[stack->ID]->getType() != group)
  692. owner->creAnims[stack->ID]->setType(group);
  693. if(owner->creAnims[stack->ID]->onFirstFrameInGroup())
  694. {
  695. if(shooting)
  696. CCS->soundh->playSound(battle_sound(attackingStack->getCreature(), shoot));
  697. else
  698. CCS->soundh->playSound(battle_sound(attackingStack->getCreature(), attack));
  699. }
  700. else if(owner->creAnims[stack->ID]->onLastFrameInGroup())
  701. {
  702. owner->creAnims[stack->ID]->setType(CCreatureAnim::HOLDING);
  703. endAnim();
  704. return; //execution of endAnim deletes this !!!
  705. }
  706. }
  707. bool CBattleAttack::checkInitialConditions()
  708. {
  709. return isEarliest(false);
  710. }
  711. CBattleAttack::CBattleAttack(CBattleInterface * _owner, const CStack * attacker, THex _dest, const CStack * defender)
  712. : CBattleStackAnimation(_owner, attacker), dest(_dest), attackedStack(defender), attackingStack(attacker)
  713. {
  714. assert(attackingStack && "attackingStack is NULL in CBattleAttack::CBattleAttack !\n");
  715. if(attackingStack->getCreature()->idNumber != 145) //catapult is allowed to attack not-creature
  716. {
  717. assert(attackedStack && "attackedStack is NULL in CBattleAttack::CBattleAttack !\n");
  718. }
  719. else //catapult can attack walls only
  720. {
  721. assert(owner->curInt->cb->battleGetWallUnderHex(_dest) >= 0);
  722. }
  723. attackingStackPosBeforeReturn = attackingStack->position;
  724. }
  725. ////melee attack
  726. bool CMeleeAttack::init()
  727. {
  728. if( !CBattleAttack::checkInitialConditions() )
  729. return false;
  730. //if(owner->creAnims[stackID]->getType()!=2)
  731. //{
  732. // return false;
  733. //}
  734. if(!attackingStack || owner->creAnims[stack->ID]->getType() == 5)
  735. {
  736. endAnim();
  737. return false;
  738. }
  739. bool toReverse = isToReverse(attackingStackPosBeforeReturn, dest, owner->creDir[stack->ID], attackedStack->doubleWide(), owner->creDir[attackedStack->ID]);
  740. if(toReverse)
  741. {
  742. owner->addNewAnim(new CReverseAnim(owner, stack, attackingStackPosBeforeReturn, true));
  743. return false;
  744. }
  745. //reversed
  746. shooting = false;
  747. static const CCreatureAnim::EAnimType mutPosToGroup[] = {CCreatureAnim::ATTACK_UP, CCreatureAnim::ATTACK_UP,
  748. CCreatureAnim::ATTACK_FRONT, CCreatureAnim::ATTACK_DOWN, CCreatureAnim::ATTACK_DOWN, CCreatureAnim::ATTACK_FRONT};
  749. int revShiftattacker = (attackingStack->attackerOwned ? -1 : 1);
  750. int mutPos = THex::mutualPosition(attackingStackPosBeforeReturn, dest);
  751. if(mutPos == -1 && attackingStack->doubleWide())
  752. {
  753. mutPos = THex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->position);
  754. }
  755. if (mutPos == -1 && attackedStack->doubleWide())
  756. {
  757. mutPos = THex::mutualPosition(attackingStackPosBeforeReturn, attackedStack->occupiedHex());
  758. }
  759. if (mutPos == -1 && attackedStack->doubleWide() && attackingStack->doubleWide())
  760. {
  761. mutPos = THex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->occupiedHex());
  762. }
  763. switch(mutPos) //attack direction
  764. {
  765. case 0: case 1: case 2: case 3: case 4: case 5:
  766. group = mutPosToGroup[mutPos];
  767. break;
  768. default:
  769. tlog1<<"Critical Error! Wrong dest in stackAttacking! dest: "<<dest<<" attacking stack pos: "<<attackingStackPosBeforeReturn<<" mutual pos: "<<mutPos<<std::endl;
  770. group = CCreatureAnim::ATTACK_FRONT;
  771. break;
  772. }
  773. return true;
  774. }
  775. void CMeleeAttack::nextFrame()
  776. {
  777. /*for(std::list<std::pair<CBattleAnimation *, bool> >::const_iterator it = owner->pendingAnims.begin(); it != owner->pendingAnims.end(); ++it)
  778. {
  779. CBattleMoveStart * anim = dynamic_cast<CBattleMoveStart *>(it->first);
  780. CReverseAnim * anim2 = dynamic_cast<CReverseAnim *>(it->first);
  781. if( (anim && anim->stackID == stackID) || (anim2 && anim2->stackID == stackID ) )
  782. return;
  783. }*/
  784. CBattleAttack::nextFrame();
  785. }
  786. void CMeleeAttack::endAnim()
  787. {
  788. CBattleAnimation::endAnim();
  789. delete this;
  790. }
  791. CMeleeAttack::CMeleeAttack(CBattleInterface * _owner, const CStack * attacker, THex _dest, const CStack * _attacked)
  792. : CBattleAttack(_owner, attacker, _dest, _attacked)
  793. {
  794. }
  795. //shooting anim
  796. bool CShootingAnim::init()
  797. {
  798. if( !CBattleAttack::checkInitialConditions() )
  799. return false;
  800. const CStack * shooter = attackingStack;
  801. if(!shooter || owner->creAnims[stack->ID]->getType() == 5)
  802. {
  803. endAnim();
  804. return false;
  805. }
  806. //projectile
  807. float projectileAngle; //in radians; if positive, projectiles goes up
  808. float straightAngle = 0.2f; //maximal angle in radians between straight horizontal line and shooting line for which shot is considered to be straight (absoulte value)
  809. int fromHex = shooter->position;
  810. projectileAngle = atan2(float(abs(dest - fromHex)/BFIELD_WIDTH), float(abs(dest - fromHex)%BFIELD_WIDTH));
  811. if(fromHex < dest)
  812. projectileAngle = -projectileAngle;
  813. SProjectileInfo spi;
  814. spi.creID = shooter->getCreature()->idNumber;
  815. spi.reverse = !shooter->attackerOwned;
  816. spi.step = 0;
  817. spi.frameNum = 0;
  818. if(vstd::contains(CGI->creh->idToProjectileSpin, spi.creID))
  819. spi.spin = CGI->creh->idToProjectileSpin[spi.creID];
  820. else
  821. {
  822. tlog2 << "Warning - no projectile spin for spi.creID " << spi.creID << std::endl;
  823. spi.spin = false;
  824. }
  825. Point xycoord = CBattleHex::getXYUnitAnim(shooter->position, true, shooter, owner);
  826. Point destcoord;
  827. if(attackedStack)
  828. {
  829. destcoord = CBattleHex::getXYUnitAnim(dest, false, attackedStack, owner);
  830. }
  831. else //catapult attack
  832. {
  833. destcoord.x = -160 + 22 * ( ((dest/BFIELD_WIDTH) + 1)%2 ) + 44 * (dest % BFIELD_WIDTH);
  834. destcoord.y = -139 + 42 * (dest/BFIELD_WIDTH);
  835. }
  836. destcoord.x += 250; destcoord.y += 210; //TODO: find a better place to shoot
  837. if(projectileAngle > straightAngle) //upper shot
  838. {
  839. spi.x = xycoord.x + 200 + shooter->getCreature()->upperRightMissleOffsetX;
  840. spi.y = xycoord.y + 100 - shooter->getCreature()->upperRightMissleOffsetY;
  841. }
  842. else if(projectileAngle < -straightAngle) //lower shot
  843. {
  844. spi.x = xycoord.x + 200 + shooter->getCreature()->lowerRightMissleOffsetX;
  845. spi.y = xycoord.y + 150 - shooter->getCreature()->lowerRightMissleOffsetY;
  846. }
  847. else //straight shot
  848. {
  849. spi.x = xycoord.x + 200 + shooter->getCreature()->rightMissleOffsetX;
  850. spi.y = xycoord.y + 125 - shooter->getCreature()->rightMissleOffsetY;
  851. }
  852. spi.lastStep = sqrt((float)((destcoord.x - spi.x)*(destcoord.x - spi.x) + (destcoord.y - spi.y) * (destcoord.y - spi.y))) / 40;
  853. if(spi.lastStep == 0)
  854. spi.lastStep = 1;
  855. spi.dx = (destcoord.x - spi.x) / spi.lastStep;
  856. spi.dy = (destcoord.y - spi.y) / spi.lastStep;
  857. //set starting frame
  858. if(spi.spin)
  859. {
  860. spi.frameNum = 0;
  861. }
  862. else
  863. {
  864. spi.frameNum = ((M_PI/2.0f - projectileAngle) / (2.0f *M_PI) + 1/((float)(2*(owner->idToProjectile[spi.creID]->ourImages.size()-1)))) * (owner->idToProjectile[spi.creID]->ourImages.size()-1);
  865. }
  866. //set delay
  867. spi.animStartDelay = CGI->creh->creatures[spi.creID]->attackClimaxFrame;
  868. owner->projectiles.push_back(spi);
  869. //attack aniamtion
  870. shooting = true;
  871. if(projectileAngle > straightAngle) //upper shot
  872. group = CCreatureAnim::SHOOT_UP;
  873. else if(projectileAngle < -straightAngle) //lower shot
  874. group = CCreatureAnim::SHOOT_DOWN;
  875. else //straight shot
  876. group = CCreatureAnim::SHOOT_FRONT;
  877. return true;
  878. }
  879. void CShootingAnim::nextFrame()
  880. {
  881. for(std::list<std::pair<CBattleAnimation *, bool> >::const_iterator it = owner->pendingAnims.begin(); it != owner->pendingAnims.end(); ++it)
  882. {
  883. CBattleMoveStart * anim = dynamic_cast<CBattleMoveStart *>(it->first);
  884. CReverseAnim * anim2 = dynamic_cast<CReverseAnim *>(it->first);
  885. if( (anim && anim->stack->ID == stack->ID) || (anim2 && anim2->stack->ID == stack->ID && anim2->priority ) )
  886. return;
  887. }
  888. CBattleAttack::nextFrame();
  889. }
  890. void CShootingAnim::endAnim()
  891. {
  892. CBattleAnimation::endAnim();
  893. delete this;
  894. }
  895. CShootingAnim::CShootingAnim(CBattleInterface * _owner, const CStack * attacker, THex _dest, const CStack * _attacked, bool _catapult, int _catapultDmg)
  896. : CBattleAttack(_owner, attacker, _dest, _attacked), catapultDamage(_catapultDmg), catapult(_catapult)
  897. {
  898. if(catapult) //catapult attack
  899. {
  900. owner->addNewAnim( new CSpellEffectAnim(owner, "SGEXPL.DEF",
  901. -130 + 22 * ( ((dest/BFIELD_WIDTH) + 1)%2 ) + 44 * (dest % BFIELD_WIDTH) + owner->pos.x,
  902. -50 + 42 * (dest/BFIELD_WIDTH) + owner->pos.y ));
  903. }
  904. }
  905. ////////////////////////
  906. void CBattleInterface::addNewAnim(CBattleAnimation * anim)
  907. {
  908. pendingAnims.push_back( std::make_pair(anim, false) );
  909. animsAreDisplayed.setn(true);
  910. }
  911. CBattleInterface::CBattleInterface(const CCreatureSet * army1, const CCreatureSet * army2, CGHeroInstance *hero1, CGHeroInstance *hero2, const SDL_Rect & myRect, CPlayerInterface * att, CPlayerInterface * defen)
  912. : queue(NULL), attackingHeroInstance(hero1), defendingHeroInstance(hero2), animCount(0),
  913. activeStack(NULL), stackToActivate(NULL), mouseHoveredStack(-1), previouslyHoveredHex(-1),
  914. currentlyHoveredHex(-1), spellDestSelectMode(false), spellToCast(NULL), siegeH(NULL),
  915. attackerInt(att), defenderInt(defen), curInt(att), animIDhelper(0), givenCommand(NULL),
  916. myTurn(false), resWindow(NULL), moveStarted(false), moveSh(-1), bresult(NULL)
  917. {
  918. ObjectConstruction h__l__p(this);
  919. if(!curInt) curInt = LOCPLINT; //may happen when we are defending during network MP game
  920. animsAreDisplayed.setn(false);
  921. pos = myRect;
  922. strongInterest = true;
  923. givenCommand = new CondSh<BattleAction *>(NULL);
  924. tacticsMode = curInt->cb->battleGetTacticDist();
  925. //create stack queue
  926. bool embedQueue = screen->h < 700;
  927. queue = new CStackQueue(embedQueue, this);
  928. if(!embedQueue && curInt->sysOpts.showQueue)
  929. {
  930. pos.y += queue->pos.h / 2; //center whole window
  931. queue->moveTo(Point(pos.x, pos.y - queue->pos.h));
  932. // queue->pos.x = pos.x;
  933. // queue->pos.y = pos.y - queue->pos.h;
  934. // pos.h += queue->pos.h;
  935. // center();
  936. }
  937. queue->update();
  938. //preparing siege info
  939. const CGTownInstance * town = curInt->cb->battleGetDefendedTown();
  940. if(town && town->hasFort())
  941. {
  942. siegeH = new SiegeHelper(town, this);
  943. }
  944. curInt->battleInt = this;
  945. //initializing armies
  946. this->army1 = army1;
  947. this->army2 = army2;
  948. std::vector<const CStack*> stacks = curInt->cb->battleGetAllStacks();
  949. BOOST_FOREACH(const CStack *s, stacks)
  950. {
  951. newStack(s);
  952. }
  953. //preparing menu background and terrain
  954. if(siegeH)
  955. {
  956. background = BitmapHandler::loadBitmap( siegeH->getSiegeName(0), false );
  957. ui8 siegeLevel = curInt->cb->battleGetSiegeLevel();
  958. if(siegeLevel >= 2) //citadel or castle
  959. {
  960. //print moat/mlip
  961. SDL_Surface * moat = BitmapHandler::loadBitmap( siegeH->getSiegeName(13) ),
  962. * mlip = BitmapHandler::loadBitmap( siegeH->getSiegeName(14) );
  963. Point moatPos = graphics->wallPositions[siegeH->town->town->typeID][10],
  964. mlipPos = graphics->wallPositions[siegeH->town->town->typeID][11];
  965. if(moat) //eg. tower has no moat
  966. blitAt(moat, moatPos.x,moatPos.y, background);
  967. if(mlip) //eg. tower has no mlip
  968. blitAt(mlip, mlipPos.x, mlipPos.y, background);
  969. SDL_FreeSurface(moat);
  970. SDL_FreeSurface(mlip);
  971. }
  972. }
  973. else
  974. {
  975. std::vector< std::string > & backref = graphics->battleBacks[ curInt->cb->battleGetBattlefieldType() ];
  976. background = BitmapHandler::loadBitmap(backref[ rand() % backref.size()], false );
  977. }
  978. //preparing menu background
  979. //graphics->blueToPlayersAdv(menu, hero1->tempOwner);
  980. //preparing graphics for displaying amounts of creatures
  981. amountNormal = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
  982. CSDL_Ext::alphaTransform(amountNormal);
  983. transformPalette(amountNormal, 0.59f, 0.19f, 0.93f);
  984. amountPositive = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
  985. CSDL_Ext::alphaTransform(amountPositive);
  986. transformPalette(amountPositive, 0.18f, 1.00f, 0.18f);
  987. amountNegative = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
  988. CSDL_Ext::alphaTransform(amountNegative);
  989. transformPalette(amountNegative, 1.00f, 0.18f, 0.18f);
  990. amountEffNeutral = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
  991. CSDL_Ext::alphaTransform(amountEffNeutral);
  992. transformPalette(amountEffNeutral, 1.00f, 1.00f, 0.18f);
  993. ////blitting menu background and terrain
  994. // blitAt(background, pos.x, pos.y);
  995. // blitAt(menu, pos.x, 556 + pos.y);
  996. //preparing buttons and console
  997. bOptions = new AdventureMapButton (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);
  998. bSurrender = new AdventureMapButton (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);
  999. bFlee = new AdventureMapButton (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);
  1000. bSurrender->block(!curInt->cb->battleCanFlee());
  1001. bFlee->block(!curInt->cb->battleCanFlee());
  1002. bAutofight = new AdventureMapButton (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);
  1003. bSpell = new AdventureMapButton (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);
  1004. bSpell->block(true);
  1005. bWait = new AdventureMapButton (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);
  1006. bDefence = new AdventureMapButton (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);
  1007. bDefence->assignedKeys.insert(SDLK_SPACE);
  1008. bConsoleUp = new AdventureMapButton (std::string(), std::string(), boost::bind(&CBattleInterface::bConsoleUpf,this), 624 + pos.x, 561 + pos.y, "ComSlide.def", SDLK_UP);
  1009. bConsoleDown = new AdventureMapButton (std::string(), std::string(), boost::bind(&CBattleInterface::bConsoleDownf,this), 624 + pos.x, 580 + pos.y, "ComSlide.def", SDLK_DOWN);
  1010. bConsoleDown->setOffset(2);
  1011. console = new CBattleConsole();
  1012. console->pos.x = 211 + pos.x;
  1013. console->pos.y = 560 + pos.y;
  1014. console->pos.w = 406;
  1015. console->pos.h = 38;
  1016. if(tacticsMode)
  1017. {
  1018. btactNext = new AdventureMapButton(std::string(), std::string(), boost::bind(&CBattleInterface::bTacticNextStack,this), 213 + pos.x, 560 + pos.y, "icm011.def", SDLK_SPACE);
  1019. btactEnd = new AdventureMapButton(std::string(), std::string(), boost::bind(&CBattleInterface::bEndTacticPhase,this), 419 + pos.x, 560 + pos.y, "icm012.def", SDLK_RETURN);
  1020. bDefence->block(true);
  1021. bWait->block(true);
  1022. menu = BitmapHandler::loadBitmap("COPLACBR.BMP");
  1023. }
  1024. else
  1025. {
  1026. menu = BitmapHandler::loadBitmap("CBAR.BMP");
  1027. btactEnd = btactNext = NULL;
  1028. }
  1029. graphics->blueToPlayersAdv(menu, curInt->playerID);
  1030. //loading hero animations
  1031. if(hero1) // attacking hero
  1032. {
  1033. int type = hero1->type->heroType;
  1034. if ( type % 2 ) type--;
  1035. if ( hero1->sex ) type++;
  1036. attackingHero = new CBattleHero(graphics->battleHeroes[type], 0, 0, false, hero1->tempOwner, hero1->tempOwner == curInt->playerID ? hero1 : NULL, this);
  1037. attackingHero->pos = genRect(attackingHero->dh->ourImages[0].bitmap->h, attackingHero->dh->ourImages[0].bitmap->w, -40 + pos.x, pos.y);
  1038. }
  1039. else
  1040. {
  1041. attackingHero = NULL;
  1042. }
  1043. if(hero2) // defending hero
  1044. {
  1045. int type = hero2->type->heroType;
  1046. if ( type % 2 ) type--;
  1047. if ( hero2->sex ) type++;
  1048. defendingHero = new CBattleHero(graphics->battleHeroes[type ], 0, 0, true, hero2->tempOwner, hero2->tempOwner == curInt->playerID ? hero2 : NULL, this);
  1049. defendingHero->pos = genRect(defendingHero->dh->ourImages[0].bitmap->h, defendingHero->dh->ourImages[0].bitmap->w, 690 + pos.x, pos.y);
  1050. }
  1051. else
  1052. {
  1053. defendingHero = NULL;
  1054. }
  1055. //preparing cells and hexes
  1056. cellBorder = BitmapHandler::loadBitmap("CCELLGRD.BMP");
  1057. CSDL_Ext::alphaTransform(cellBorder);
  1058. cellShade = BitmapHandler::loadBitmap("CCELLSHD.BMP");
  1059. CSDL_Ext::alphaTransform(cellShade);
  1060. for(int h=0; h<BFIELD_SIZE; ++h)
  1061. {
  1062. bfield[h].myNumber = h;
  1063. int x = 14 + ((h/BFIELD_WIDTH)%2==0 ? 22 : 0) + 44*(h%BFIELD_WIDTH);
  1064. int y = 86 + 42 * (h/BFIELD_WIDTH);
  1065. bfield[h].pos = genRect(cellShade->h, cellShade->w, x + pos.x, y + pos.y);
  1066. bfield[h].accessible = true;
  1067. bfield[h].myInterface = this;
  1068. }
  1069. //locking occupied positions on batlefield
  1070. BOOST_FOREACH(const CStack *s, stacks) //stacks gained at top of this function
  1071. if(s->position >= 0) //turrets have position < 0
  1072. bfield[s->position].accessible = false;
  1073. //loading projectiles for units
  1074. BOOST_FOREACH(const CStack *s, stacks)
  1075. {
  1076. int creID = (s->getCreature()->idNumber == 149) ? CGI->creh->factionToTurretCreature[siegeH->town->town->typeID] : s->getCreature()->idNumber; //id of creature whose shots should be loaded
  1077. if(s->getCreature()->isShooting() && vstd::contains(CGI->creh->idToProjectile, creID))
  1078. {
  1079. CDefHandler *&projectile = idToProjectile[s->getCreature()->idNumber];
  1080. projectile = CDefHandler::giveDef(CGI->creh->idToProjectile[creID]);
  1081. if(projectile->ourImages.size() > 2) //add symmetric images
  1082. {
  1083. for(int k = projectile->ourImages.size()-2; k > 1; --k)
  1084. {
  1085. Cimage ci;
  1086. ci.bitmap = CSDL_Ext::rotate01(projectile->ourImages[k].bitmap);
  1087. ci.groupNumber = 0;
  1088. ci.imName = std::string();
  1089. projectile->ourImages.push_back(ci);
  1090. }
  1091. }
  1092. for(int s=0; s<projectile->ourImages.size(); ++s) //alpha transforming
  1093. {
  1094. CSDL_Ext::alphaTransform(projectile->ourImages[s].bitmap);
  1095. }
  1096. }
  1097. }
  1098. //preparing graphic with cell borders
  1099. cellBorders = CSDL_Ext::newSurface(background->w, background->h, cellBorder);
  1100. //copying palette
  1101. for(int g=0; g<cellBorder->format->palette->ncolors; ++g) //we assume that cellBorders->format->palette->ncolors == 256
  1102. {
  1103. cellBorders->format->palette->colors[g] = cellBorder->format->palette->colors[g];
  1104. }
  1105. //palette copied
  1106. for(int i=0; i<BFIELD_HEIGHT; ++i) //rows
  1107. {
  1108. for(int j=0; j<BFIELD_WIDTH-2; ++j) //columns
  1109. {
  1110. int x = 58 + (i%2==0 ? 22 : 0) + 44*j;
  1111. int y = 86 + 42 * i;
  1112. for(int cellX = 0; cellX < cellBorder->w; ++cellX)
  1113. {
  1114. for(int cellY = 0; cellY < cellBorder->h; ++cellY)
  1115. {
  1116. if(y+cellY < cellBorders->h && x+cellX < cellBorders->w)
  1117. * ((Uint8*)cellBorders->pixels + (y+cellY) * cellBorders->pitch + (x+cellX)) |= * ((Uint8*)cellBorder->pixels + cellY * cellBorder->pitch + cellX);
  1118. }
  1119. }
  1120. }
  1121. }
  1122. backgroundWithHexes = CSDL_Ext::newSurface(background->w, background->h, screen);
  1123. //preparing obstacle defs
  1124. std::vector<CObstacleInstance> obst = curInt->cb->battleGetAllObstacles();
  1125. for(int t=0; t<obst.size(); ++t)
  1126. {
  1127. idToObstacle[obst[t].ID] = CDefHandler::giveDef(CGI->heroh->obstacles.find(obst[t].ID)->second.defName);
  1128. for(int n=0; n<idToObstacle[obst[t].ID]->ourImages.size(); ++n)
  1129. {
  1130. SDL_SetColorKey(idToObstacle[obst[t].ID]->ourImages[n].bitmap, SDL_SRCCOLORKEY, SDL_MapRGB(idToObstacle[obst[t].ID]->ourImages[n].bitmap->format,0,255,255));
  1131. }
  1132. }
  1133. for (int i = 0; i < ARRAY_COUNT(bfield); i++)
  1134. {
  1135. children.push_back(&bfield[i]);
  1136. }
  1137. if(tacticsMode)
  1138. {
  1139. active = 1;
  1140. bTacticNextStack();
  1141. active = 0;
  1142. }
  1143. }
  1144. CBattleInterface::~CBattleInterface()
  1145. {
  1146. if (active) //dirty fix for #485
  1147. {
  1148. deactivate();
  1149. }
  1150. SDL_FreeSurface(background);
  1151. SDL_FreeSurface(menu);
  1152. SDL_FreeSurface(amountNormal);
  1153. SDL_FreeSurface(amountNegative);
  1154. SDL_FreeSurface(amountPositive);
  1155. SDL_FreeSurface(amountEffNeutral);
  1156. SDL_FreeSurface(cellBorders);
  1157. SDL_FreeSurface(backgroundWithHexes);
  1158. delete bOptions;
  1159. delete bSurrender;
  1160. delete bFlee;
  1161. delete bAutofight;
  1162. delete bSpell;
  1163. delete bWait;
  1164. delete bDefence;
  1165. delete bConsoleUp;
  1166. delete bConsoleDown;
  1167. delete console;
  1168. delete givenCommand;
  1169. delete attackingHero;
  1170. delete defendingHero;
  1171. delete queue;
  1172. SDL_FreeSurface(cellBorder);
  1173. SDL_FreeSurface(cellShade);
  1174. for(std::map< int, CCreatureAnimation * >::iterator g=creAnims.begin(); g!=creAnims.end(); ++g)
  1175. delete g->second;
  1176. for(std::map< int, CDefHandler * >::iterator g=idToProjectile.begin(); g!=idToProjectile.end(); ++g)
  1177. delete g->second;
  1178. for(std::map< int, CDefHandler * >::iterator g=idToObstacle.begin(); g!=idToObstacle.end(); ++g)
  1179. delete g->second;
  1180. delete siegeH;
  1181. curInt->battleInt = NULL;
  1182. }
  1183. void CBattleInterface::setPrintCellBorders(bool set)
  1184. {
  1185. curInt->sysOpts.printCellBorders = set;
  1186. curInt->sysOpts.settingsChanged();
  1187. redrawBackgroundWithHexes(activeStack);
  1188. GH.totalRedraw();
  1189. }
  1190. void CBattleInterface::setPrintStackRange(bool set)
  1191. {
  1192. curInt->sysOpts.printStackRange = set;
  1193. curInt->sysOpts.settingsChanged();
  1194. redrawBackgroundWithHexes(activeStack);
  1195. GH.totalRedraw();
  1196. }
  1197. void CBattleInterface::setPrintMouseShadow(bool set)
  1198. {
  1199. curInt->sysOpts.printMouseShadow = set;
  1200. curInt->sysOpts.settingsChanged();
  1201. }
  1202. void CBattleInterface::activate()
  1203. {
  1204. activateKeys();
  1205. activateMouseMove();
  1206. activateRClick();
  1207. bOptions->activate();
  1208. bSurrender->activate();
  1209. bFlee->activate();
  1210. bAutofight->activate();
  1211. bSpell->activate();
  1212. bWait->activate();
  1213. bDefence->activate();
  1214. for(int b=0; b<BFIELD_SIZE; ++b)
  1215. {
  1216. bfield[b].activate();
  1217. }
  1218. if(attackingHero)
  1219. attackingHero->activate();
  1220. if(defendingHero)
  1221. defendingHero->activate();
  1222. if(curInt->sysOpts.showQueue)
  1223. queue->activate();
  1224. if(tacticsMode)
  1225. {
  1226. btactNext->activate();
  1227. btactEnd->activate();
  1228. }
  1229. else
  1230. {
  1231. bConsoleUp->activate();
  1232. bConsoleDown->activate();
  1233. }
  1234. LOCPLINT->cingconsole->activate();
  1235. }
  1236. void CBattleInterface::deactivate()
  1237. {
  1238. deactivateKeys();
  1239. deactivateMouseMove();
  1240. deactivateRClick();
  1241. bOptions->deactivate();
  1242. bSurrender->deactivate();
  1243. bFlee->deactivate();
  1244. bAutofight->deactivate();
  1245. bSpell->deactivate();
  1246. bWait->deactivate();
  1247. bDefence->deactivate();
  1248. for(int b=0; b<BFIELD_SIZE; ++b)
  1249. {
  1250. bfield[b].deactivate();
  1251. }
  1252. if(attackingHero)
  1253. attackingHero->deactivate();
  1254. if(defendingHero)
  1255. defendingHero->deactivate();
  1256. if(curInt->sysOpts.showQueue)
  1257. queue->deactivate();
  1258. if(tacticsMode)
  1259. {
  1260. btactNext->deactivate();
  1261. btactEnd->deactivate();
  1262. }
  1263. else
  1264. {
  1265. bConsoleUp->deactivate();
  1266. bConsoleDown->deactivate();
  1267. }
  1268. LOCPLINT->cingconsole->deactivate();
  1269. }
  1270. void CBattleInterface::show(SDL_Surface * to)
  1271. {
  1272. std::vector<const CStack*> stacks = curInt->cb->battleGetAllStacks(); //used in a few places
  1273. ++animCount;
  1274. if(!to) //"evaluating" to
  1275. to = screen;
  1276. SDL_Rect buf;
  1277. SDL_GetClipRect(to, &buf);
  1278. SDL_SetClipRect(to, &pos);
  1279. //printing background and hexes
  1280. if(activeStack != NULL && creAnims[activeStack->ID]->getType() != 0) //show everything with range
  1281. {
  1282. blitAt(backgroundWithHexes, pos.x, pos.y, to);
  1283. }
  1284. else
  1285. {
  1286. //showing background
  1287. blitAt(background, pos.x, pos.y, to);
  1288. if(curInt->sysOpts.printCellBorders)
  1289. {
  1290. CSDL_Ext::blit8bppAlphaTo24bpp(cellBorders, NULL, to, &pos);
  1291. }
  1292. }
  1293. //printing hovered cell
  1294. for(int b=0; b<BFIELD_SIZE; ++b)
  1295. {
  1296. if(bfield[b].strictHovered && bfield[b].hovered)
  1297. {
  1298. if(previouslyHoveredHex == -1) previouslyHoveredHex = b; //something to start with
  1299. if(currentlyHoveredHex == -1) currentlyHoveredHex = b; //something to start with
  1300. if(currentlyHoveredHex != b) //repair hover info
  1301. {
  1302. previouslyHoveredHex = currentlyHoveredHex;
  1303. currentlyHoveredHex = b;
  1304. }
  1305. //print shade
  1306. if(spellToCast) //when casting spell
  1307. {
  1308. //calculating spell schoold level
  1309. const CSpell & spToCast = *CGI->spellh->spells[spellToCast->additionalInfo];
  1310. ui8 schoolLevel = 0;
  1311. if( activeStack->attackerOwned )
  1312. {
  1313. if(attackingHeroInstance)
  1314. schoolLevel = attackingHeroInstance->getSpellSchoolLevel(&spToCast);
  1315. }
  1316. else
  1317. {
  1318. if(defendingHeroInstance)
  1319. schoolLevel = defendingHeroInstance->getSpellSchoolLevel(&spToCast);
  1320. }
  1321. //obtaining range and printing it
  1322. std::set<ui16> shaded = spToCast.rangeInHexes(b, schoolLevel);
  1323. for(std::set<ui16>::iterator it = shaded.begin(); it != shaded.end(); ++it) //for spells with range greater then one hex
  1324. {
  1325. if(curInt->sysOpts.printMouseShadow && (*it % BFIELD_WIDTH != 0) && (*it % BFIELD_WIDTH != 16))
  1326. {
  1327. int x = 14 + ((*it/BFIELD_WIDTH)%2==0 ? 22 : 0) + 44*(*it%BFIELD_WIDTH) + pos.x;
  1328. int y = 86 + 42 * (*it/BFIELD_WIDTH) + pos.y;
  1329. CSDL_Ext::blit8bppAlphaTo24bpp(cellShade, NULL, to, &genRect(cellShade->h, cellShade->w, x, y));
  1330. }
  1331. }
  1332. }
  1333. else if(curInt->sysOpts.printMouseShadow) //when not casting spell
  1334. {
  1335. int x = 14 + ((b/BFIELD_WIDTH)%2==0 ? 22 : 0) + 44*(b%BFIELD_WIDTH) + pos.x;
  1336. int y = 86 + 42 * (b/BFIELD_WIDTH) + pos.y;
  1337. CSDL_Ext::blit8bppAlphaTo24bpp(cellShade, NULL, to, &genRect(cellShade->h, cellShade->w, x, y));
  1338. }
  1339. }
  1340. }
  1341. SDL_SetClipRect(to, &buf); //restoring previous clip_rect
  1342. //prevents blitting outside this window
  1343. SDL_GetClipRect(to, &buf);
  1344. SDL_SetClipRect(to, &pos);
  1345. //preparing obstacles to be shown
  1346. std::vector<CObstacleInstance> obstacles = curInt->cb->battleGetAllObstacles();
  1347. std::multimap<THex, int> hexToObstacle;
  1348. for(int b=0; b<obstacles.size(); ++b)
  1349. {
  1350. THex position = CGI->heroh->obstacles.find(obstacles[b].ID)->second.getMaxBlocked(obstacles[b].pos);
  1351. hexToObstacle.insert(std::make_pair(position, b));
  1352. }
  1353. ////showing units //a lot of work...
  1354. std::vector<const CStack *> stackAliveByHex[BFIELD_SIZE];
  1355. //double loop because dead stacks should be printed first
  1356. BOOST_FOREACH(const CStack *s, stacks)
  1357. {
  1358. if(creAnims.find(s->ID) == creAnims.end()) //eg. for summoned but not yet handled stacks
  1359. continue;
  1360. if(creAnims[s->ID]->getType() != 5 && s->position >= 0) //don't show turrets here
  1361. stackAliveByHex[s->position].push_back(s);
  1362. }
  1363. std::vector<const CStack *> stackDeadByHex[BFIELD_SIZE];
  1364. BOOST_FOREACH(const CStack *s, stacks)
  1365. {
  1366. if(creAnims.find(s->ID) == creAnims.end()) //eg. for summoned but not yet handled stacks
  1367. continue;
  1368. if(creAnims[s->ID]->getType() == 5)
  1369. stackDeadByHex[s->position].push_back(s);
  1370. }
  1371. //handle animations
  1372. for(std::list<std::pair<CBattleAnimation *, bool> >::iterator it = pendingAnims.begin(); it != pendingAnims.end(); ++it)
  1373. {
  1374. if(!it->first) //this animation should be deleted
  1375. continue;
  1376. if(!it->second)
  1377. {
  1378. it->second = it->first->init();
  1379. }
  1380. if(it->second && it->first)
  1381. it->first->nextFrame();
  1382. }
  1383. //delete anims
  1384. int preSize = pendingAnims.size();
  1385. for(std::list<std::pair<CBattleAnimation *, bool> >::iterator it = pendingAnims.begin(); it != pendingAnims.end(); ++it)
  1386. {
  1387. if(it->first == NULL)
  1388. {
  1389. pendingAnims.erase(it);
  1390. it = pendingAnims.begin();
  1391. break;
  1392. }
  1393. }
  1394. if(preSize > 0 && pendingAnims.size() == 0)
  1395. {
  1396. //action finished, restore the interface
  1397. if(!active)
  1398. activate();
  1399. //activation of next stack
  1400. if(pendingAnims.size() == 0 && stackToActivate != NULL)
  1401. {
  1402. activateStack();
  1403. }
  1404. //anims ended
  1405. animsAreDisplayed.setn(false);
  1406. }
  1407. for(int b=0; b<BFIELD_SIZE; ++b) //showing dead stacks
  1408. {
  1409. for(size_t v=0; v<stackDeadByHex[b].size(); ++v)
  1410. {
  1411. 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
  1412. }
  1413. }
  1414. std::vector<const CStack *> flyingStacks; //flying stacks should be displayed later, over other stacks and obstacles
  1415. for(int b=0; b<BFIELD_SIZE; ++b) //showing alive stacks
  1416. {
  1417. for(size_t v=0; v<stackAliveByHex[b].size(); ++v)
  1418. {
  1419. const CStack *s = stackAliveByHex[b][v];
  1420. if(!s->hasBonusOfType(Bonus::FLYING) || creAnims[s->ID]->getType() != 0)
  1421. showAliveStack(s, to);
  1422. else
  1423. flyingStacks.push_back(s);
  1424. }
  1425. //showing obstacles
  1426. std::pair<std::multimap<THex, int>::const_iterator, std::multimap<THex, int>::const_iterator> obstRange =
  1427. hexToObstacle.equal_range(b);
  1428. for(std::multimap<THex, int>::const_iterator it = obstRange.first; it != obstRange.second; ++it)
  1429. {
  1430. CObstacleInstance & curOb = obstacles[it->second];
  1431. std::pair<si16, si16> shift = CGI->heroh->obstacles.find(curOb.ID)->second.posShift;
  1432. int x = ((curOb.pos/BFIELD_WIDTH)%2==0 ? 22 : 0) + 44*(curOb.pos%BFIELD_WIDTH) + pos.x + shift.first;
  1433. int y = 86 + 42 * (curOb.pos/BFIELD_WIDTH) + pos.y + shift.second;
  1434. std::vector<Cimage> &images = idToObstacle[curOb.ID]->ourImages; //reference to animation of obstacle
  1435. blitAt(images[((animCount+1)/(4/curInt->sysOpts.animSpeed))%images.size()].bitmap, x, y, to);
  1436. }
  1437. //showing wall pieces
  1438. showPieceOfWall(to, b, stacks);
  1439. }
  1440. for(int b=0; b<flyingStacks.size(); ++b) //showing flying stacks
  1441. showAliveStack(flyingStacks[b], to);
  1442. //units shown
  1443. //showing hero animations
  1444. if(attackingHero)
  1445. attackingHero->show(to);
  1446. if(defendingHero)
  1447. defendingHero->show(to);
  1448. projectileShowHelper(to);//showing projectiles
  1449. //showing spell effects
  1450. if(battleEffects.size())
  1451. {
  1452. for(std::list<SBattleEffect>::iterator it = battleEffects.begin(); it!=battleEffects.end(); ++it)
  1453. {
  1454. SDL_Surface * bitmapToBlit = it->anim->ourImages[(it->frame)%it->anim->ourImages.size()].bitmap;
  1455. SDL_BlitSurface(bitmapToBlit, NULL, to, &genRect(bitmapToBlit->h, bitmapToBlit->w, it->x, it->y));
  1456. }
  1457. }
  1458. SDL_SetClipRect(to, &buf); //restoring previous clip_rect
  1459. //showing menu background and console
  1460. blitAt(menu, pos.x, 556 + pos.y, to);
  1461. if(tacticsMode)
  1462. {
  1463. btactNext->show(to);
  1464. btactEnd->show(to);
  1465. }
  1466. else
  1467. {
  1468. console->show(to);
  1469. bConsoleUp->show(to);
  1470. bConsoleDown->show(to);
  1471. }
  1472. //showing buttons
  1473. bOptions->showAll(to);
  1474. bSurrender->showAll(to);
  1475. bFlee->showAll(to);
  1476. bAutofight->showAll(to);
  1477. bSpell->showAll(to);
  1478. bWait->showAll(to);
  1479. bDefence->showAll(to);
  1480. //showing window with result of battle
  1481. if(resWindow)
  1482. {
  1483. resWindow->show(to);
  1484. }
  1485. //showing in-game console
  1486. LOCPLINT->cingconsole->show(to);
  1487. Rect posWithQueue = Rect(pos.x, pos.y, 800, 600);
  1488. if(curInt->sysOpts.showQueue)
  1489. {
  1490. if(!queue->embedded)
  1491. {
  1492. posWithQueue.y -= queue->pos.h;
  1493. posWithQueue.h += queue->pos.h;
  1494. }
  1495. //showing queue
  1496. if(!bresult)
  1497. queue->showAll(to);
  1498. else
  1499. queue->blitBg(to); //blit only background, stacks are deleted
  1500. }
  1501. //printing border around interface
  1502. if(screen->w != 800 || screen->h !=600)
  1503. {
  1504. CMessage::drawBorder(curInt->playerID,to,posWithQueue.w + 28, posWithQueue.h + 28, posWithQueue.x-14, posWithQueue.y-15);
  1505. }
  1506. }
  1507. void CBattleInterface::keyPressed(const SDL_KeyboardEvent & key)
  1508. {
  1509. if(key.keysym.sym == SDLK_q && key.state == SDL_PRESSED)
  1510. {
  1511. if(curInt->sysOpts.showQueue) //hide queue
  1512. hideQueue();
  1513. else
  1514. showQueue();
  1515. curInt->sysOpts.settingsChanged();
  1516. }
  1517. else if(key.keysym.sym == SDLK_ESCAPE && spellDestSelectMode)
  1518. {
  1519. endCastingSpell();
  1520. }
  1521. }
  1522. void CBattleInterface::mouseMoved(const SDL_MouseMotionEvent &sEvent)
  1523. {
  1524. if(activeStack!= NULL && !spellDestSelectMode)
  1525. {
  1526. mouseHoveredStack = -1;
  1527. int myNumber = -1; //number of hovered tile
  1528. for(int g=0; g<BFIELD_SIZE; ++g)
  1529. {
  1530. if(bfield[g].hovered && bfield[g].strictHovered)
  1531. {
  1532. myNumber = g;
  1533. break;
  1534. }
  1535. }
  1536. if(myNumber == -1)
  1537. {
  1538. CCS->curh->changeGraphic(1, 6);
  1539. if(console->whoSetAlter == 0)
  1540. {
  1541. console->alterTxt = "";
  1542. }
  1543. }
  1544. else
  1545. {
  1546. if(std::find(shadedHexes.begin(),shadedHexes.end(),myNumber) == shadedHexes.end())
  1547. {
  1548. const CStack *shere = curInt->cb->battleGetStackByPos(myNumber);
  1549. const CStack *sactive = activeStack;
  1550. if(shere)
  1551. {
  1552. if(shere->owner == curInt->playerID) //our stack
  1553. {
  1554. if(sactive->hasBonusOfType(Bonus::HEALER))
  1555. {
  1556. //display the possibility to heal this creature
  1557. CCS->curh->changeGraphic(1,17);
  1558. }
  1559. else
  1560. {
  1561. //info about creature
  1562. CCS->curh->changeGraphic(1,5);
  1563. }
  1564. //setting console text
  1565. char buf[500];
  1566. sprintf(buf, CGI->generaltexth->allTexts[297].c_str(), shere->count == 1 ? shere->getCreature()->nameSing.c_str() : shere->getCreature()->namePl.c_str());
  1567. console->alterTxt = buf;
  1568. console->whoSetAlter = 0;
  1569. mouseHoveredStack = shere->ID;
  1570. if(creAnims[shere->ID]->getType() == CCreatureAnim::HOLDING && creAnims[shere->ID]->framesInGroup(CCreatureAnim::MOUSEON) > 0)
  1571. {
  1572. creAnims[shere->ID]->playOnce(CCreatureAnim::MOUSEON);
  1573. }
  1574. }
  1575. else if(curInt->cb->battleCanShoot(activeStack,myNumber)) //we can shoot enemy
  1576. {
  1577. if(curInt->cb->battleHasDistancePenalty(activeStack, myNumber) ||
  1578. curInt->cb->battleHasWallPenalty(activeStack, myNumber))
  1579. {
  1580. CCS->curh->changeGraphic(1,15);
  1581. }
  1582. else
  1583. {
  1584. CCS->curh->changeGraphic(1,3);
  1585. }
  1586. //setting console text
  1587. char buf[500];
  1588. //calculating estimated dmg
  1589. std::pair<ui32, ui32> estimatedDmg = curInt->cb->battleEstimateDamage(sactive, shere);
  1590. std::ostringstream estDmg;
  1591. estDmg << estimatedDmg.first << " - " << estimatedDmg.second;
  1592. //printing
  1593. sprintf(buf, CGI->generaltexth->allTexts[296].c_str(), shere->count == 1 ? shere->getCreature()->nameSing.c_str() : shere->getCreature()->namePl.c_str(), sactive->shots, estDmg.str().c_str());
  1594. console->alterTxt = buf;
  1595. console->whoSetAlter = 0;
  1596. }
  1597. else if(isTileAttackable(myNumber)) //available enemy (melee attackable)
  1598. {
  1599. CCursorHandler *cursor = CCS->curh;
  1600. const CBattleHex &hoveredHex = bfield[myNumber];
  1601. const double subdividingAngle = 2.0*M_PI/6.0; // Divide a hex into six sectors.
  1602. const double hexMidX = hoveredHex.pos.x + hoveredHex.pos.w/2;
  1603. const double hexMidY = hoveredHex.pos.y + hoveredHex.pos.h/2;
  1604. const double cursorHexAngle = M_PI - atan2(hexMidY - cursor->ypos, cursor->xpos - hexMidX) + subdividingAngle/2;
  1605. const double sector = fmod(cursorHexAngle/subdividingAngle, 6.0);
  1606. const int zigzagCorrection = !((myNumber/BFIELD_WIDTH)%2); // Off-by-one correction needed to deal with the odd battlefield rows.
  1607. std::vector<int> sectorCursor; // From left to bottom left.
  1608. sectorCursor.push_back(8);
  1609. sectorCursor.push_back(9);
  1610. sectorCursor.push_back(10);
  1611. sectorCursor.push_back(11);
  1612. sectorCursor.push_back(12);
  1613. sectorCursor.push_back(7);
  1614. const bool doubleWide = activeStack->doubleWide();
  1615. bool aboveAttackable = true, belowAttackable = true;
  1616. // Exclude directions which cannot be attacked from.
  1617. // Check to the left.
  1618. if (myNumber%BFIELD_WIDTH <= 1 || !vstd::contains(shadedHexes, myNumber - 1))
  1619. {
  1620. sectorCursor[0] = -1;
  1621. }
  1622. // Check top left, top right as well as above for 2-hex creatures.
  1623. if (myNumber/BFIELD_WIDTH == 0)
  1624. {
  1625. sectorCursor[1] = -1;
  1626. sectorCursor[2] = -1;
  1627. aboveAttackable = false;
  1628. }
  1629. else
  1630. {
  1631. if (doubleWide)
  1632. {
  1633. bool attackRow[4] = {true, true, true, true};
  1634. if (myNumber%BFIELD_WIDTH <= 1 || !vstd::contains(shadedHexes, myNumber - BFIELD_WIDTH - 2 + zigzagCorrection))
  1635. attackRow[0] = false;
  1636. if (!vstd::contains(shadedHexes, myNumber - BFIELD_WIDTH - 1 + zigzagCorrection))
  1637. attackRow[1] = false;
  1638. if (!vstd::contains(shadedHexes, myNumber - BFIELD_WIDTH + zigzagCorrection))
  1639. attackRow[2] = false;
  1640. if (myNumber%BFIELD_WIDTH >= BFIELD_WIDTH - 2 || !vstd::contains(shadedHexes, myNumber - BFIELD_WIDTH + 1 + zigzagCorrection))
  1641. attackRow[3] = false;
  1642. if (!(attackRow[0] && attackRow[1]))
  1643. sectorCursor[1] = -1;
  1644. if (!(attackRow[1] && attackRow[2]))
  1645. aboveAttackable = false;
  1646. if (!(attackRow[2] && attackRow[3]))
  1647. sectorCursor[2] = -1;
  1648. }
  1649. else
  1650. {
  1651. if (!vstd::contains(shadedHexes, myNumber - BFIELD_WIDTH - 1 + zigzagCorrection))
  1652. sectorCursor[1] = -1;
  1653. if (!vstd::contains(shadedHexes, myNumber - BFIELD_WIDTH + zigzagCorrection))
  1654. sectorCursor[2] = -1;
  1655. }
  1656. }
  1657. // Check to the right.
  1658. if (myNumber%BFIELD_WIDTH >= BFIELD_WIDTH - 2 || !vstd::contains(shadedHexes, myNumber + 1))
  1659. {
  1660. sectorCursor[3] = -1;
  1661. }
  1662. // Check bottom right, bottom left as well as below for 2-hex creatures.
  1663. if (myNumber/BFIELD_WIDTH == BFIELD_HEIGHT - 1)
  1664. {
  1665. sectorCursor[4] = -1;
  1666. sectorCursor[5] = -1;
  1667. belowAttackable = false;
  1668. }
  1669. else
  1670. {
  1671. if (doubleWide)
  1672. {
  1673. bool attackRow[4] = {true, true, true, true};
  1674. if (myNumber%BFIELD_WIDTH <= 1 || !vstd::contains(shadedHexes, myNumber + BFIELD_WIDTH - 2 + zigzagCorrection))
  1675. attackRow[0] = false;
  1676. if (!vstd::contains(shadedHexes, myNumber + BFIELD_WIDTH - 1 + zigzagCorrection))
  1677. attackRow[1] = false;
  1678. if (!vstd::contains(shadedHexes, myNumber + BFIELD_WIDTH + zigzagCorrection))
  1679. attackRow[2] = false;
  1680. if (myNumber%BFIELD_WIDTH >= BFIELD_WIDTH - 2 || !vstd::contains(shadedHexes, myNumber + BFIELD_WIDTH + 1 + zigzagCorrection))
  1681. attackRow[3] = false;
  1682. if (!(attackRow[0] && attackRow[1]))
  1683. sectorCursor[5] = -1;
  1684. if (!(attackRow[1] && attackRow[2]))
  1685. belowAttackable = false;
  1686. if (!(attackRow[2] && attackRow[3]))
  1687. sectorCursor[4] = -1;
  1688. }
  1689. else
  1690. {
  1691. if (!vstd::contains(shadedHexes, myNumber + BFIELD_WIDTH + zigzagCorrection))
  1692. sectorCursor[4] = -1;
  1693. if (!vstd::contains(shadedHexes, myNumber + BFIELD_WIDTH - 1 + zigzagCorrection))
  1694. sectorCursor[5] = -1;
  1695. }
  1696. }
  1697. // Determine index from sector.
  1698. int cursorIndex;
  1699. if (doubleWide)
  1700. {
  1701. sectorCursor.insert(sectorCursor.begin() + 5, belowAttackable ? 13 : -1);
  1702. sectorCursor.insert(sectorCursor.begin() + 2, aboveAttackable ? 14 : -1);
  1703. if (sector < 1.5)
  1704. cursorIndex = sector;
  1705. else if (sector >= 1.5 && sector < 2.5)
  1706. cursorIndex = 2;
  1707. else if (sector >= 2.5 && sector < 4.5)
  1708. cursorIndex = (int) sector + 1;
  1709. else if (sector >= 4.5 && sector < 5.5)
  1710. cursorIndex = 6;
  1711. else
  1712. cursorIndex = (int) sector + 2;
  1713. }
  1714. else
  1715. {
  1716. cursorIndex = sector;
  1717. }
  1718. // Find the closest direction attackable, starting with the right one.
  1719. // FIXME: Is this really how the original H3 client does it?
  1720. int i = 0;
  1721. while (sectorCursor[(cursorIndex + i)%sectorCursor.size()] == -1)
  1722. i = i <= 0 ? 1 - i : -i; // 0, 1, -1, 2, -2, 3, -3 etc..
  1723. cursor->changeGraphic(1, sectorCursor[(cursorIndex + i)%sectorCursor.size()]);
  1724. //setting console info
  1725. char buf[500];
  1726. //calculating estimated dmg
  1727. std::pair<ui32, ui32> estimatedDmg = curInt->cb->battleEstimateDamage(sactive, shere);
  1728. std::ostringstream estDmg;
  1729. estDmg << estimatedDmg.first << " - " << estimatedDmg.second;
  1730. //printing
  1731. sprintf(buf, CGI->generaltexth->allTexts[36].c_str(), shere->count == 1 ? shere->getCreature()->nameSing.c_str() : shere->getCreature()->namePl.c_str(), estDmg.str().c_str());
  1732. console->alterTxt = buf;
  1733. console->whoSetAlter = 0;
  1734. }
  1735. else //unavailable enemy
  1736. {
  1737. CCS->curh->changeGraphic(1,0);
  1738. console->alterTxt = "";
  1739. console->whoSetAlter = 0;
  1740. }
  1741. }
  1742. else if( sactive && sactive->hasBonusOfType(Bonus::CATAPULT) && isCatapultAttackable(myNumber) ) //catapulting
  1743. {
  1744. CCS->curh->changeGraphic(1,16);
  1745. console->alterTxt = "";
  1746. console->whoSetAlter = 0;
  1747. }
  1748. else //empty unavailable tile
  1749. {
  1750. CCS->curh->changeGraphic(1,0);
  1751. console->alterTxt = "";
  1752. console->whoSetAlter = 0;
  1753. }
  1754. }
  1755. else //available tile
  1756. {
  1757. //setting console text and cursor
  1758. const CStack *sactive = activeStack;
  1759. if(sactive) //there can be a moment when stack is dead ut next is not yet activated
  1760. {
  1761. char buf[500];
  1762. if(sactive->hasBonusOfType(Bonus::FLYING))
  1763. {
  1764. CCS->curh->changeGraphic(1,2);
  1765. sprintf(buf, CGI->generaltexth->allTexts[295].c_str(), sactive->count == 1 ? sactive->getCreature()->nameSing.c_str() : sactive->getCreature()->namePl.c_str());
  1766. }
  1767. else
  1768. {
  1769. CCS->curh->changeGraphic(1,1);
  1770. sprintf(buf, CGI->generaltexth->allTexts[294].c_str(), sactive->count == 1 ? sactive->getCreature()->nameSing.c_str() : sactive->getCreature()->namePl.c_str());
  1771. }
  1772. console->alterTxt = buf;
  1773. console->whoSetAlter = 0;
  1774. }
  1775. }
  1776. }
  1777. }
  1778. else if(spellDestSelectMode)
  1779. {
  1780. int myNumber = -1; //number of hovered tile
  1781. for(int g=0; g<BFIELD_SIZE; ++g)
  1782. {
  1783. if(bfield[g].hovered && bfield[g].strictHovered)
  1784. {
  1785. myNumber = g;
  1786. break;
  1787. }
  1788. }
  1789. if(myNumber == -1)
  1790. {
  1791. CCS->curh->changeGraphic(1, 0);
  1792. //setting console text
  1793. console->alterTxt = CGI->generaltexth->allTexts[23];
  1794. console->whoSetAlter = 0;
  1795. }
  1796. else
  1797. {
  1798. //get dead stack if we cast resurrection or animate dead
  1799. const CStack * stackUnder = curInt->cb->battleGetStackByPos(myNumber, spellToCast->additionalInfo != 38 && spellToCast->additionalInfo != 39);
  1800. if(stackUnder && spellToCast->additionalInfo == 39 && !stackUnder->hasBonusOfType(Bonus::UNDEAD)) //animate dead can be cast only on undead creatures
  1801. stackUnder = NULL;
  1802. bool whichCase; //for cases 1, 2 and 3
  1803. switch(spellSelMode)
  1804. {
  1805. case 1:
  1806. whichCase = stackUnder && curInt->playerID == stackUnder->owner;
  1807. break;
  1808. case 2:
  1809. whichCase = stackUnder && curInt->playerID != stackUnder->owner;
  1810. break;
  1811. case 3:
  1812. whichCase = stackUnder;
  1813. break;
  1814. }
  1815. switch(spellSelMode)
  1816. {
  1817. case 0:
  1818. CCS->curh->changeGraphic(3, 0);
  1819. //setting console text
  1820. char buf[500];
  1821. sprintf(buf, CGI->generaltexth->allTexts[26].c_str(), CGI->spellh->spells[spellToCast->additionalInfo]->name.c_str());
  1822. console->alterTxt = buf;
  1823. console->whoSetAlter = 0;
  1824. break;
  1825. case 1: case 2: case 3:
  1826. if( whichCase )
  1827. {
  1828. CCS->curh->changeGraphic(3, 0);
  1829. //setting console text
  1830. char buf[500];
  1831. std::string creName = stackUnder->count > 1 ? stackUnder->getCreature()->namePl : stackUnder->getCreature()->nameSing;
  1832. sprintf(buf, CGI->generaltexth->allTexts[27].c_str(), CGI->spellh->spells[spellToCast->additionalInfo]->name.c_str(), creName.c_str());
  1833. console->alterTxt = buf;
  1834. console->whoSetAlter = 0;
  1835. break;
  1836. }
  1837. else
  1838. {
  1839. CCS->curh->changeGraphic(1, 0);
  1840. //setting console text
  1841. console->alterTxt = CGI->generaltexth->allTexts[23];
  1842. console->whoSetAlter = 0;
  1843. }
  1844. break;
  1845. case 4: //TODO: implement this case
  1846. if( blockedByObstacle(myNumber) )
  1847. {
  1848. CCS->curh->changeGraphic(3, 0);
  1849. }
  1850. else
  1851. {
  1852. CCS->curh->changeGraphic(1, 0);
  1853. }
  1854. break;
  1855. }
  1856. }
  1857. }
  1858. }
  1859. void CBattleInterface::clickRight(tribool down, bool previousState)
  1860. {
  1861. if(!down && spellDestSelectMode)
  1862. {
  1863. endCastingSpell();
  1864. }
  1865. }
  1866. void CBattleInterface::bOptionsf()
  1867. {
  1868. if(spellDestSelectMode) //we are casting a spell
  1869. return;
  1870. CCS->curh->changeGraphic(0,0);
  1871. SDL_Rect temp_rect = genRect(431, 481, 160, 84);
  1872. CBattleOptionsWindow * optionsWin = new CBattleOptionsWindow(temp_rect, this);
  1873. GH.pushInt(optionsWin);
  1874. }
  1875. void CBattleInterface::bSurrenderf()
  1876. {
  1877. if(spellDestSelectMode) //we are casting a spell
  1878. return;
  1879. }
  1880. void CBattleInterface::bFleef()
  1881. {
  1882. if(spellDestSelectMode) //we are casting a spell
  1883. return;
  1884. if( curInt->cb->battleCanFlee() )
  1885. {
  1886. CFunctionList<void()> ony = boost::bind(&CBattleInterface::reallyFlee,this);
  1887. curInt->showYesNoDialog(CGI->generaltexth->allTexts[28],std::vector<SComponent*>(), ony, 0, false);
  1888. }
  1889. else
  1890. {
  1891. std::vector<SComponent*> comps;
  1892. std::string heroName;
  1893. //calculating fleeing hero's name
  1894. if(attackingHeroInstance)
  1895. if(attackingHeroInstance->tempOwner == curInt->cb->getMyColor())
  1896. heroName = attackingHeroInstance->name;
  1897. if(defendingHeroInstance)
  1898. if(defendingHeroInstance->tempOwner == curInt->cb->getMyColor())
  1899. heroName = defendingHeroInstance->name;
  1900. //calculating text
  1901. char buffer[1000];
  1902. sprintf(buffer, CGI->generaltexth->allTexts[340].c_str(), heroName.c_str());
  1903. //printing message
  1904. curInt->showInfoDialog(std::string(buffer), comps);
  1905. }
  1906. }
  1907. void CBattleInterface::reallyFlee()
  1908. {
  1909. giveCommand(4,0,0);
  1910. CCS->curh->changeGraphic(0, 0);
  1911. }
  1912. void CBattleInterface::bAutofightf()
  1913. {
  1914. if(spellDestSelectMode) //we are casting a spell
  1915. return;
  1916. }
  1917. void CBattleInterface::bSpellf()
  1918. {
  1919. if(spellDestSelectMode) //we are casting a spell
  1920. return;
  1921. CCS->curh->changeGraphic(0,0);
  1922. const CGHeroInstance * chi = NULL;
  1923. if(attackingHeroInstance->tempOwner == curInt->playerID)
  1924. chi = attackingHeroInstance;
  1925. else
  1926. chi = defendingHeroInstance;
  1927. CSpellWindow * spellWindow = new CSpellWindow(genRect(595, 620, (conf.cc.resx - 620)/2, (conf.cc.resy - 595)/2), chi, curInt);
  1928. GH.pushInt(spellWindow);
  1929. }
  1930. void CBattleInterface::bWaitf()
  1931. {
  1932. if(spellDestSelectMode) //we are casting a spell
  1933. return;
  1934. if(activeStack != NULL)
  1935. giveCommand(8,0,activeStack->ID);
  1936. }
  1937. void CBattleInterface::bDefencef()
  1938. {
  1939. if(spellDestSelectMode) //we are casting a spell
  1940. return;
  1941. if(activeStack != NULL)
  1942. giveCommand(3,0,activeStack->ID);
  1943. }
  1944. void CBattleInterface::bConsoleUpf()
  1945. {
  1946. if(spellDestSelectMode) //we are casting a spell
  1947. return;
  1948. console->scrollUp();
  1949. }
  1950. void CBattleInterface::bConsoleDownf()
  1951. {
  1952. if(spellDestSelectMode) //we are casting a spell
  1953. return;
  1954. console->scrollDown();
  1955. }
  1956. void CBattleInterface::newStack(const CStack * stack)
  1957. {
  1958. Point coords = CBattleHex::getXYUnitAnim(stack->position, stack->owner == attackingHeroInstance->tempOwner, stack, this);;
  1959. if(stack->position < 0) //turret
  1960. {
  1961. const CCreature & turretCreature = *CGI->creh->creatures[ CGI->creh->factionToTurretCreature[siegeH->town->town->typeID] ];
  1962. creAnims[stack->ID] = new CCreatureAnimation(turretCreature.animDefName);
  1963. }
  1964. else
  1965. {
  1966. creAnims[stack->ID] = new CCreatureAnimation(stack->getCreature()->animDefName);
  1967. }
  1968. creAnims[stack->ID]->setType(CCreatureAnim::HOLDING);
  1969. creAnims[stack->ID]->pos = Rect(coords.x, coords.y, creAnims[stack->ID]->fullWidth, creAnims[stack->ID]->fullHeight);
  1970. creDir[stack->ID] = stack->attackerOwned;
  1971. }
  1972. void CBattleInterface::stackRemoved(const CStack * stack)
  1973. {
  1974. int stackID = stack->ID;
  1975. delete creAnims[stackID];
  1976. creAnims.erase(stackID);
  1977. creDir.erase(stackID);
  1978. }
  1979. void CBattleInterface::stackActivated(const CStack * stack)
  1980. {
  1981. //givenCommand = NULL;
  1982. stackToActivate = stack;
  1983. if(pendingAnims.size() == 0)
  1984. activateStack();
  1985. }
  1986. void CBattleInterface::stackMoved(const CStack * stack, THex destHex, bool endMoving, int distance)
  1987. {
  1988. addNewAnim(new CBattleStackMoved(this, stack, destHex, endMoving, distance));
  1989. waitForAnims();
  1990. }
  1991. void CBattleInterface::stacksAreAttacked(std::vector<SStackAttackedInfo> attackedInfos)
  1992. {
  1993. for(int h = 0; h < attackedInfos.size(); ++h)
  1994. {
  1995. addNewAnim(new CDefenceAnim(attackedInfos[h], this));
  1996. }
  1997. waitForAnims();
  1998. }
  1999. void CBattleInterface::stackAttacking( const CStack * attacker, THex dest, const CStack * attacked, bool shooting )
  2000. {
  2001. if (shooting)
  2002. {
  2003. addNewAnim(new CShootingAnim(this, attacker, dest, attacked));
  2004. }
  2005. else
  2006. {
  2007. addNewAnim(new CMeleeAttack(this, attacker, dest, attacked));
  2008. }
  2009. waitForAnims();
  2010. }
  2011. void CBattleInterface::newRoundFirst( int round )
  2012. {
  2013. //handle regeneration
  2014. std::vector<const CStack*> stacks = curInt->cb->battleGetStacks(); //gets only alive stacks
  2015. BOOST_FOREACH(const CStack *s, stacks)
  2016. {
  2017. //don't show animation when no HP is regenerated
  2018. if (s->firstHPleft == s->MaxHealth())
  2019. {
  2020. continue;
  2021. }
  2022. if( s->hasBonusOfType(Bonus::HP_REGENERATION))
  2023. displayEffect(74, s->position);
  2024. if( s->hasBonusOfType(Bonus::FULL_HP_REGENERATION, 0))
  2025. displayEffect(4, s->position);
  2026. if( s->hasBonusOfType(Bonus::FULL_HP_REGENERATION, 1))
  2027. displayEffect(74, s->position);
  2028. }
  2029. waitForAnims();
  2030. }
  2031. void CBattleInterface::newRound(int number)
  2032. {
  2033. console->addText(CGI->generaltexth->allTexts[412]);
  2034. //unlock spellbook
  2035. //bSpell->block(!curInt->cb->battleCanCastSpell());
  2036. //don't unlock spellbook - this should be done when we have axctive creature
  2037. }
  2038. void CBattleInterface::giveCommand(ui8 action, THex tile, ui32 stack, si32 additional)
  2039. {
  2040. if(!curInt->cb->battleGetStackByID(stack) && action != 1 && action != 4 && action != 5)
  2041. {
  2042. return;
  2043. }
  2044. BattleAction * ba = new BattleAction(); //is deleted in CPlayerInterface::activeStack()
  2045. ba->side = defendingHeroInstance ? (curInt->playerID == defendingHeroInstance->tempOwner) : false;
  2046. ba->actionType = action;
  2047. ba->destinationTile = tile;
  2048. ba->stackNumber = stack;
  2049. ba->additionalInfo = additional;
  2050. //some basic validations
  2051. switch(action)
  2052. {
  2053. case 6:
  2054. assert(curInt->cb->battleGetStackByPos(additional)); //stack to attack must exist
  2055. case 2: case 7: case 9:
  2056. assert(tile < BFIELD_SIZE);
  2057. break;
  2058. }
  2059. if(!tacticsMode)
  2060. {
  2061. myTurn = false;
  2062. activeStack = NULL;
  2063. givenCommand->setn(ba);
  2064. }
  2065. else
  2066. {
  2067. curInt->cb->battleMakeTacticAction(ba);
  2068. delNull(ba);
  2069. bTacticNextStack();
  2070. }
  2071. }
  2072. bool CBattleInterface::isTileAttackable(const THex & number) const
  2073. {
  2074. for(size_t b=0; b<shadedHexes.size(); ++b)
  2075. {
  2076. if(THex::mutualPosition(shadedHexes[b], number) != -1 || shadedHexes[b] == number)
  2077. return true;
  2078. }
  2079. return false;
  2080. }
  2081. bool CBattleInterface::blockedByObstacle(THex hex) const
  2082. {
  2083. std::vector<CObstacleInstance> obstacles = curInt->cb->battleGetAllObstacles();
  2084. std::set<THex> coveredHexes;
  2085. for(int b = 0; b < obstacles.size(); ++b)
  2086. {
  2087. std::vector<THex> blocked = CGI->heroh->obstacles.find(obstacles[b].ID)->second.getBlocked(obstacles[b].pos);
  2088. for(int w = 0; w < blocked.size(); ++w)
  2089. coveredHexes.insert(blocked[w]);
  2090. }
  2091. return vstd::contains(coveredHexes, hex);
  2092. }
  2093. bool CBattleInterface::isCatapultAttackable(THex hex) const
  2094. {
  2095. if(!siegeH)
  2096. return false;
  2097. int wallUnder = curInt->cb->battleGetWallUnderHex(hex);
  2098. if(wallUnder == -1)
  2099. return false;
  2100. return curInt->cb->battleGetWallState(wallUnder) < 3;
  2101. }
  2102. const CGHeroInstance * CBattleInterface::getActiveHero()
  2103. {
  2104. const CStack * attacker = activeStack;
  2105. if (!attacker)
  2106. {
  2107. return NULL;
  2108. }
  2109. if (attacker->attackerOwned)
  2110. {
  2111. return attackingHeroInstance;
  2112. }
  2113. return defendingHeroInstance;
  2114. }
  2115. void CBattleInterface::hexLclicked(int whichOne)
  2116. {
  2117. const CStack * actSt = activeStack;
  2118. const CStack* dest = curInt->cb->battleGetStackByPos(whichOne); //creature at destination tile; -1 if there is no one
  2119. if(!actSt)
  2120. {
  2121. tlog3 << "Hex l-clicked when no active stack!\n";
  2122. return;
  2123. }
  2124. if( ((whichOne%BFIELD_WIDTH)!=0 && (whichOne%BFIELD_WIDTH)!=(BFIELD_WIDTH-1)) //if player is trying to attack enemey unit or move creature stack
  2125. || (actSt->hasBonusOfType(Bonus::CATAPULT) && !spellDestSelectMode || dest ) //enemy's first aid tent can stand there and we want to shoot it
  2126. )
  2127. {
  2128. if(!myTurn)
  2129. return; //we are not permit to do anything
  2130. if(spellDestSelectMode)
  2131. {
  2132. //checking destination
  2133. bool allowCasting = true;
  2134. bool onlyAlive = spellToCast->additionalInfo != 38 && spellToCast->additionalInfo != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  2135. switch(spellSelMode)
  2136. {
  2137. case 1:
  2138. if(!curInt->cb->battleGetStackByPos(whichOne, onlyAlive) || curInt->playerID != curInt->cb->battleGetStackByPos(whichOne, onlyAlive)->owner )
  2139. allowCasting = false;
  2140. break;
  2141. case 2:
  2142. if(!curInt->cb->battleGetStackByPos(whichOne, onlyAlive) || curInt->playerID == curInt->cb->battleGetStackByPos(whichOne, onlyAlive)->owner )
  2143. allowCasting = false;
  2144. break;
  2145. case 3:
  2146. if(!curInt->cb->battleGetStackByPos(whichOne, onlyAlive))
  2147. allowCasting = false;
  2148. break;
  2149. case 4:
  2150. if(!blockedByObstacle(whichOne))
  2151. allowCasting = false;
  2152. case 5: //teleport
  2153. const CSpell *s = CGI->spellh->spells[spellToCast->additionalInfo];
  2154. ui8 skill = getActiveHero()->getSpellSchoolLevel(s); //skill level
  2155. if (!curInt->cb->battleCanTeleportTo(activeStack, whichOne, skill))
  2156. {
  2157. allowCasting = false;
  2158. }
  2159. break;
  2160. }
  2161. //destination checked
  2162. if(allowCasting)
  2163. {
  2164. spellToCast->destinationTile = whichOne;
  2165. curInt->cb->battleMakeAction(spellToCast);
  2166. endCastingSpell();
  2167. }
  2168. }
  2169. else //we don't cast any spell
  2170. {
  2171. if(!dest || !dest->alive()) //no creature at that tile
  2172. {
  2173. if(std::find(shadedHexes.begin(),shadedHexes.end(),whichOne)!=shadedHexes.end())// and it's in our range
  2174. {
  2175. CCS->curh->changeGraphic(1, 6); //cursor should be changed
  2176. if(activeStack->doubleWide())
  2177. {
  2178. std::vector<THex> acc = curInt->cb->battleGetAvailableHexes(activeStack, false);
  2179. int shiftedDest = whichOne + (activeStack->attackerOwned ? 1 : -1);
  2180. if(vstd::contains(acc, whichOne))
  2181. giveCommand(2,whichOne,activeStack->ID);
  2182. else if(vstd::contains(acc, shiftedDest))
  2183. giveCommand(2,shiftedDest,activeStack->ID);
  2184. }
  2185. else
  2186. {
  2187. giveCommand(2,whichOne,activeStack->ID);
  2188. }
  2189. }
  2190. else if(actSt->hasBonusOfType(Bonus::CATAPULT) && isCatapultAttackable(whichOne)) //attacking (catapult)
  2191. {
  2192. giveCommand(9,whichOne,activeStack->ID);
  2193. }
  2194. }
  2195. else if(dest->owner != actSt->owner
  2196. && curInt->cb->battleCanShoot(activeStack, whichOne) ) //shooting
  2197. {
  2198. CCS->curh->changeGraphic(1, 6); //cursor should be changed
  2199. giveCommand(7,whichOne,activeStack->ID);
  2200. }
  2201. else if(dest->owner != actSt->owner) //attacking
  2202. {
  2203. const CStack * actStack = activeStack;
  2204. int attackFromHex = -1; //hex from which we will attack chosen stack
  2205. switch(CCS->curh->number)
  2206. {
  2207. case 12: //from bottom right
  2208. {
  2209. bool doubleWide = actStack->doubleWide();
  2210. int destHex = whichOne + ( (whichOne/BFIELD_WIDTH)%2 ? BFIELD_WIDTH : BFIELD_WIDTH+1 ) +
  2211. (actStack->attackerOwned && doubleWide ? 1 : 0);
  2212. if(vstd::contains(shadedHexes, destHex))
  2213. attackFromHex = destHex;
  2214. else if(actStack->attackerOwned) //if we are attacker
  2215. {
  2216. if(vstd::contains(shadedHexes, destHex+1))
  2217. attackFromHex = destHex+1;
  2218. }
  2219. else //if we are defender
  2220. {
  2221. if(vstd::contains(shadedHexes, destHex-1))
  2222. attackFromHex = destHex-1;
  2223. }
  2224. break;
  2225. }
  2226. case 7: //from bottom left
  2227. {
  2228. int destHex = whichOne + ( (whichOne/BFIELD_WIDTH)%2 ? BFIELD_WIDTH-1 : BFIELD_WIDTH );
  2229. if(vstd::contains(shadedHexes, destHex))
  2230. attackFromHex = destHex;
  2231. else if(actStack->attackerOwned) //if we are attacker
  2232. {
  2233. if(vstd::contains(shadedHexes, destHex+1))
  2234. attackFromHex = destHex+1;
  2235. }
  2236. else //if we are defender
  2237. {
  2238. if(vstd::contains(shadedHexes, destHex-1))
  2239. attackFromHex = destHex-1;
  2240. }
  2241. break;
  2242. }
  2243. case 8: //from left
  2244. {
  2245. if(actStack->doubleWide() && !actStack->attackerOwned)
  2246. {
  2247. std::vector<THex> acc = curInt->cb->battleGetAvailableHexes(activeStack, false);
  2248. if(vstd::contains(acc, whichOne))
  2249. attackFromHex = whichOne - 1;
  2250. else
  2251. attackFromHex = whichOne - 2;
  2252. }
  2253. else
  2254. {
  2255. attackFromHex = whichOne - 1;
  2256. }
  2257. break;
  2258. }
  2259. case 9: //from top left
  2260. {
  2261. int destHex = whichOne - ( (whichOne/BFIELD_WIDTH)%2 ? BFIELD_WIDTH+1 : BFIELD_WIDTH );
  2262. if(vstd::contains(shadedHexes, destHex))
  2263. attackFromHex = destHex;
  2264. else if(actStack->attackerOwned) //if we are attacker
  2265. {
  2266. if(vstd::contains(shadedHexes, destHex+1))
  2267. attackFromHex = destHex+1;
  2268. }
  2269. else //if we are defender
  2270. {
  2271. if(vstd::contains(shadedHexes, destHex-1))
  2272. attackFromHex = destHex-1;
  2273. }
  2274. break;
  2275. }
  2276. case 10: //from top right
  2277. {
  2278. bool doubleWide = actStack->doubleWide();
  2279. int destHex = whichOne - ( (whichOne/BFIELD_WIDTH)%2 ? BFIELD_WIDTH : BFIELD_WIDTH-1 ) +
  2280. (actStack->attackerOwned && doubleWide ? 1 : 0);
  2281. if(vstd::contains(shadedHexes, destHex))
  2282. attackFromHex = destHex;
  2283. else if(actStack->attackerOwned) //if we are attacker
  2284. {
  2285. if(vstd::contains(shadedHexes, destHex+1))
  2286. attackFromHex = destHex+1;
  2287. }
  2288. else //if we are defender
  2289. {
  2290. if(vstd::contains(shadedHexes, destHex-1))
  2291. attackFromHex = destHex-1;
  2292. }
  2293. break;
  2294. }
  2295. case 11: //from right
  2296. {
  2297. if(actStack->doubleWide() && actStack->attackerOwned)
  2298. {
  2299. std::vector<THex> acc = curInt->cb->battleGetAvailableHexes(activeStack, false);
  2300. if(vstd::contains(acc, whichOne))
  2301. attackFromHex = whichOne + 1;
  2302. else
  2303. attackFromHex = whichOne + 2;
  2304. }
  2305. else
  2306. {
  2307. attackFromHex = whichOne + 1;
  2308. }
  2309. break;
  2310. }
  2311. case 13: //from bottom
  2312. {
  2313. int destHex = whichOne + ( (whichOne/BFIELD_WIDTH)%2 ? BFIELD_WIDTH : BFIELD_WIDTH+1 );
  2314. if(vstd::contains(shadedHexes, destHex))
  2315. attackFromHex = destHex;
  2316. else if(attackingHeroInstance->tempOwner == curInt->cb->getMyColor()) //if we are attacker
  2317. {
  2318. if(vstd::contains(shadedHexes, destHex+1))
  2319. attackFromHex = destHex+1;
  2320. }
  2321. else //if we are defender
  2322. {
  2323. if(vstd::contains(shadedHexes, destHex-1))
  2324. attackFromHex = destHex-1;
  2325. }
  2326. break;
  2327. }
  2328. case 14: //from top
  2329. {
  2330. int destHex = whichOne - ( (whichOne/BFIELD_WIDTH)%2 ? BFIELD_WIDTH : BFIELD_WIDTH-1 );
  2331. if(vstd::contains(shadedHexes, destHex))
  2332. attackFromHex = destHex;
  2333. else if(attackingHeroInstance->tempOwner == curInt->cb->getMyColor()) //if we are attacker
  2334. {
  2335. if(vstd::contains(shadedHexes, destHex+1))
  2336. attackFromHex = destHex+1;
  2337. }
  2338. else //if we are defender
  2339. {
  2340. if(vstd::contains(shadedHexes, destHex-1))
  2341. attackFromHex = destHex-1;
  2342. }
  2343. break;
  2344. }
  2345. }
  2346. if(attackFromHex >= 0) //we can be in this line when unreachable creature is L - clicked (as of revision 1308)
  2347. {
  2348. giveCommand(6, attackFromHex, activeStack->ID, whichOne);
  2349. CCS->curh->changeGraphic(1, 6); //cursor should be changed
  2350. }
  2351. }
  2352. else if (actSt->hasBonusOfType(Bonus::HEALER) && actSt->owner == dest->owner) //friendly creature we can heal
  2353. {
  2354. giveCommand(12, whichOne, activeStack->ID); //command healing
  2355. CCS->curh->changeGraphic(1, 6); //cursor should be changed
  2356. }
  2357. }
  2358. }
  2359. }
  2360. void CBattleInterface::stackIsCatapulting(const CatapultAttack & ca)
  2361. {
  2362. for(std::set< std::pair< std::pair< ui8, si16 >, ui8> >::const_iterator it = ca.attackedParts.begin(); it != ca.attackedParts.end(); ++it)
  2363. {
  2364. const CStack * stack = curInt->cb->battleGetStackByID(ca.attacker);
  2365. addNewAnim(new CShootingAnim(this, stack, it->first.second, NULL, true, it->second));
  2366. SDL_FreeSurface(siegeH->walls[it->first.first + 2]);
  2367. siegeH->walls[it->first.first + 2] = BitmapHandler::loadBitmap(
  2368. siegeH->getSiegeName(it->first.first + 2, curInt->cb->battleGetWallState(it->first.first)) );
  2369. }
  2370. waitForAnims();
  2371. }
  2372. void CBattleInterface::battleFinished(const BattleResult& br)
  2373. {
  2374. bresult = &br;
  2375. LOCPLINT->pim->unlock();
  2376. animsAreDisplayed.waitUntil(false);
  2377. LOCPLINT->pim->lock();
  2378. displayBattleFinished();
  2379. }
  2380. void CBattleInterface::displayBattleFinished()
  2381. {
  2382. CCS->curh->changeGraphic(0,0);
  2383. SDL_Rect temp_rect = genRect(561, 470, (screen->w - 800)/2 + 165, (screen->h - 600)/2 + 19);
  2384. CCS->musich->stopMusic();
  2385. resWindow = new CBattleResultWindow(*bresult, temp_rect, this);
  2386. GH.pushInt(resWindow);
  2387. }
  2388. void CBattleInterface::spellCast( const BattleSpellCast * sc )
  2389. {
  2390. const CSpell &spell = *CGI->spellh->spells[sc->id];
  2391. //spell opening battle is cast when no stack is active
  2392. if(sc->castedByHero && ( activeStack == NULL || sc->side == !activeStack->attackerOwned) )
  2393. bSpell->block(true);
  2394. std::vector< std::string > anims; //for magic arrow and ice bolt
  2395. if (vstd::contains(CCS->soundh->spellSounds, &spell))
  2396. CCS->soundh->playSound(CCS->soundh->spellSounds[&spell]);
  2397. switch(sc->id)
  2398. {
  2399. case 15: //magic arrow
  2400. {
  2401. //initialization of anims
  2402. 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");
  2403. }
  2404. case 16: //ice bolt
  2405. {
  2406. if(anims.size() == 0) //initialization of anims
  2407. {
  2408. 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");
  2409. }
  2410. } //end of ice bolt only part
  2411. { //common ice bolt and magic arrow part
  2412. //initial variables
  2413. std::string animToDisplay;
  2414. Point srccoord = (sc->side ? Point(770, 60) : Point(30, 60)) + pos;
  2415. Point destcoord = CBattleHex::getXYUnitAnim(sc->tile, !sc->side, curInt->cb->battleGetStackByPos(sc->tile), this); //position attacked by arrow
  2416. destcoord.x += 250; destcoord.y += 240;
  2417. //animation angle
  2418. float angle = atan2(float(destcoord.x - srccoord.x), float(destcoord.y - srccoord.y));
  2419. bool Vflip = false;
  2420. if (angle < 0)
  2421. {
  2422. Vflip = true;
  2423. angle = -angle;
  2424. }
  2425. //choosing animation by angle
  2426. if(angle > 1.50)
  2427. animToDisplay = anims[0];
  2428. else if(angle > 1.20)
  2429. animToDisplay = anims[1];
  2430. else if(angle > 0.90)
  2431. animToDisplay = anims[2];
  2432. else if(angle > 0.60)
  2433. animToDisplay = anims[3];
  2434. else
  2435. animToDisplay = anims[4];
  2436. //displaying animation
  2437. CDefEssential * animDef = CDefHandler::giveDefEss(animToDisplay);
  2438. int steps = sqrt((float)((destcoord.x - srccoord.x)*(destcoord.x - srccoord.x) + (destcoord.y - srccoord.y) * (destcoord.y - srccoord.y))) / 40;
  2439. if(steps <= 0)
  2440. steps = 1;
  2441. int dx = (destcoord.x - srccoord.x - animDef->ourImages[0].bitmap->w)/steps, dy = (destcoord.y - srccoord.y - animDef->ourImages[0].bitmap->h)/steps;
  2442. delete animDef;
  2443. addNewAnim(new CSpellEffectAnim(this, animToDisplay, srccoord.x, srccoord.y, dx, dy, Vflip));
  2444. break; //for 15 and 16 cases
  2445. }
  2446. case 17: //lightning bolt
  2447. case 77: //thunderbolt
  2448. displayEffect(1, sc->tile);
  2449. displayEffect(spell.mainEffectAnim, sc->tile);
  2450. break;
  2451. case 35: //dispel
  2452. case 37: //cure
  2453. case 38: //resurrection
  2454. case 39: //animate dead
  2455. case 78: //dispel helpful spells
  2456. for(std::set<ui32>::const_iterator it = sc->affectedCres.begin(); it != sc->affectedCres.end(); ++it)
  2457. {
  2458. displayEffect(spell.mainEffectAnim, curInt->cb->battleGetStackByID(*it, false)->position);
  2459. }
  2460. break;
  2461. case 66: case 67: case 68: case 69: //summon elemental
  2462. addNewAnim(new CDummyAnim(this, 2));
  2463. break;
  2464. } //switch(sc->id)
  2465. //support for resistance
  2466. for(int j=0; j<sc->resisted.size(); ++j)
  2467. {
  2468. int tile = curInt->cb->battleGetStackByID(sc->resisted[j])->position;
  2469. displayEffect(78, tile);
  2470. }
  2471. //displaying message in console
  2472. if(sc->affectedCres.size() == 1)
  2473. {
  2474. std::string text = CGI->generaltexth->allTexts[195];
  2475. if(sc->castedByHero)
  2476. {
  2477. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetFightingHero(sc->side)->name);
  2478. }
  2479. else
  2480. {
  2481. boost::algorithm::replace_first(text, "%s", "Creature"); //TODO: better fix
  2482. }
  2483. boost::algorithm::replace_first(text, "%s", CGI->spellh->spells[sc->id]->name);
  2484. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin(), false)->getCreature()->namePl );
  2485. console->addText(text);
  2486. }
  2487. else
  2488. {
  2489. std::string text = CGI->generaltexth->allTexts[196];
  2490. if(sc->castedByHero)
  2491. {
  2492. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetFightingHero(sc->side)->name);
  2493. }
  2494. else
  2495. {
  2496. boost::algorithm::replace_first(text, "%s", "Creature"); //TODO: better fix
  2497. }
  2498. boost::algorithm::replace_first(text, "%s", CGI->spellh->spells[sc->id]->name);
  2499. console->addText(text);
  2500. }
  2501. if(sc->dmgToDisplay != 0)
  2502. {
  2503. std::string dmgInfo = CGI->generaltexth->allTexts[343].substr(1, CGI->generaltexth->allTexts[343].size() - 1);
  2504. boost::algorithm::replace_first(dmgInfo, "%d", boost::lexical_cast<std::string>(sc->dmgToDisplay));
  2505. console->addText(dmgInfo);
  2506. }
  2507. waitForAnims();
  2508. }
  2509. void CBattleInterface::battleStacksEffectsSet(const SetStackEffect & sse)
  2510. {
  2511. int effID = sse.effect.back().sid;
  2512. if(effID != -1) //can be -1 for defensive stance effect
  2513. {
  2514. for(std::vector<ui32>::const_iterator ci = sse.stacks.begin(); ci!=sse.stacks.end(); ++ci)
  2515. {
  2516. displayEffect(CGI->spellh->spells[effID]->mainEffectAnim, curInt->cb->battleGetStackByID(*ci)->position);
  2517. }
  2518. }
  2519. else if (sse.stacks.size() == 1 && sse.effect.size() == 1)
  2520. {
  2521. const Bonus & bns = sse.effect.back();
  2522. if (bns.source == Bonus::OTHER && bns.type == Bonus::PRIMARY_SKILL)
  2523. {
  2524. //defensive stance (I hope)
  2525. const CStack * stack = LOCPLINT->cb->battleGetStackByID(*sse.stacks.begin());
  2526. int txtid = 120;
  2527. if(stack->count != 1)
  2528. txtid++; //move to plural text
  2529. char txt[4000];
  2530. int val = stack->Defense() - (stack->Defense() * 100 )/ (100 + bns.val);
  2531. sprintf(txt, CGI->generaltexth->allTexts[txtid].c_str(), (stack->count != 1) ? stack->getCreature()->namePl.c_str() : stack->getCreature()->nameSing.c_str(), val);
  2532. console->addText(txt);
  2533. }
  2534. }
  2535. if (activeStack != NULL) //it can be -1 when a creature casts effect
  2536. {
  2537. redrawBackgroundWithHexes(activeStack);
  2538. }
  2539. }
  2540. void CBattleInterface::castThisSpell(int spellID)
  2541. {
  2542. BattleAction * ba = new BattleAction;
  2543. ba->actionType = BattleAction::HERO_SPELL;
  2544. ba->additionalInfo = spellID; //spell number
  2545. ba->destinationTile = -1;
  2546. ba->stackNumber = (attackingHeroInstance->tempOwner == curInt->playerID) ? -1 : -2;
  2547. ba->side = defendingHeroInstance ? (curInt->playerID == defendingHeroInstance->tempOwner) : false;
  2548. spellToCast = ba;
  2549. spellDestSelectMode = true;
  2550. //choosing possible tragets
  2551. const CGHeroInstance * castingHero = (attackingHeroInstance->tempOwner == curInt->playerID) ? attackingHeroInstance : defendingHeroInstance;
  2552. const CSpell & spell = *CGI->spellh->spells[spellID];
  2553. spellSelMode = 0;
  2554. if(spell.attributes.find("CREATURE_TARGET") != std::string::npos) //spell to be cast on one specific creature
  2555. {
  2556. switch(spell.positiveness)
  2557. {
  2558. case -1 :
  2559. spellSelMode = 2;
  2560. break;
  2561. case 0:
  2562. spellSelMode = 3;
  2563. break;
  2564. case 1:
  2565. spellSelMode = 1;
  2566. break;
  2567. }
  2568. }
  2569. if(spell.attributes.find("CREATURE_TARGET_1") != std::string::npos ||
  2570. spell.attributes.find("CREATURE_TARGET_2") != std::string::npos) //spell to be cast on a specific creature but massive on expert
  2571. {
  2572. if(castingHero && castingHero->getSpellSchoolLevel(&spell) < 3)
  2573. {
  2574. switch(spell.positiveness)
  2575. {
  2576. case -1 :
  2577. spellSelMode = 2;
  2578. break;
  2579. case 0:
  2580. spellSelMode = 3;
  2581. break;
  2582. case 1:
  2583. spellSelMode = 1;
  2584. break;
  2585. }
  2586. }
  2587. else
  2588. {
  2589. spellSelMode = -1;
  2590. }
  2591. }
  2592. if(spell.attributes.find("OBSTACLE_TARGET") != std::string::npos) //spell to be cast on an obstacle
  2593. {
  2594. spellSelMode = 4;
  2595. }
  2596. if(spell.range[ castingHero->getSpellSchoolLevel(&spell) ] == "X") //spell has no range
  2597. {
  2598. spellSelMode = -1;
  2599. }
  2600. if(spell.id == 63) //teleport
  2601. {
  2602. spellSelMode = 5;
  2603. }
  2604. if(spell.range[ castingHero->getSpellSchoolLevel(&spell) ].size() > 1) //spell has many-hex range
  2605. {
  2606. spellSelMode = 0;
  2607. }
  2608. if(spellSelMode == -1) //user does not have to select location
  2609. {
  2610. spellToCast->destinationTile = -1;
  2611. curInt->cb->battleMakeAction(spellToCast);
  2612. endCastingSpell();
  2613. }
  2614. else
  2615. {
  2616. CCS->curh->changeGraphic(3, 0);
  2617. }
  2618. }
  2619. void CBattleInterface::displayEffect(ui32 effect, int destTile)
  2620. {
  2621. addNewAnim(new CSpellEffectAnim(this, effect, destTile));
  2622. }
  2623. void CBattleInterface::setAnimSpeed(int set)
  2624. {
  2625. curInt->sysOpts.animSpeed = set;
  2626. curInt->sysOpts.settingsChanged();
  2627. }
  2628. int CBattleInterface::getAnimSpeed() const
  2629. {
  2630. return curInt->sysOpts.animSpeed;
  2631. curInt->sysOpts.settingsChanged();
  2632. }
  2633. void CBattleInterface::activateStack()
  2634. {
  2635. activeStack = stackToActivate;
  2636. stackToActivate = NULL;
  2637. const CStack *s = activeStack;
  2638. myTurn = true;
  2639. if(attackerInt && defenderInt) //hotseat -> need to pick which interface "takes over" as active
  2640. curInt = attackerInt->playerID == s->owner ? attackerInt : defenderInt;
  2641. queue->update();
  2642. redrawBackgroundWithHexes(activeStack);
  2643. bWait->block(vstd::contains(s->state, WAITING)); //block waiting button if stack has been already waiting
  2644. //block cast spell button if hero doesn't have a spellbook
  2645. bSpell->block(!curInt->cb->battleCanCastSpell());
  2646. bSurrender->block((curInt == attackerInt ? defendingHeroInstance : attackingHeroInstance) == NULL);
  2647. bFlee->block(!curInt->cb->battleCanFlee());
  2648. GH.fakeMouseMove();
  2649. if(!pendingAnims.size() && !active)
  2650. activate();
  2651. }
  2652. float CBattleInterface::getAnimSpeedMultiplier() const
  2653. {
  2654. switch(curInt->sysOpts.animSpeed)
  2655. {
  2656. case 1:
  2657. return 3.5f;
  2658. case 2:
  2659. return 2.2f;
  2660. case 4:
  2661. return 1.0f;
  2662. default:
  2663. return 0.0f;
  2664. }
  2665. }
  2666. void CBattleInterface::endCastingSpell()
  2667. {
  2668. assert(spellDestSelectMode);
  2669. delete spellToCast;
  2670. spellToCast = NULL;
  2671. spellDestSelectMode = false;
  2672. CCS->curh->changeGraphic(1, 6);
  2673. }
  2674. void CBattleInterface::showAliveStack(const CStack *stack, SDL_Surface * to)
  2675. {
  2676. int ID = stack->ID;
  2677. if(creAnims.find(ID) == creAnims.end()) //eg. for summoned but not yet handled stacks
  2678. return;
  2679. int animType = creAnims[ID]->getType();
  2680. int affectingSpeed = curInt->sysOpts.animSpeed;
  2681. if(animType == 1 || animType == 2) //standing stacks should not stand faster :)
  2682. affectingSpeed = 2;
  2683. bool incrementFrame = (animCount%(4/affectingSpeed)==0) && animType!=5 && animType!=20 && animType!=2;
  2684. if(animType == 2)
  2685. {
  2686. if(standingFrame.find(ID)!=standingFrame.end())
  2687. {
  2688. incrementFrame = (animCount%(8/affectingSpeed)==0);
  2689. if(incrementFrame)
  2690. {
  2691. ++standingFrame[ID];
  2692. if(standingFrame[ID] == creAnims[ID]->framesInGroup(CCreatureAnim::HOLDING))
  2693. {
  2694. standingFrame.erase(standingFrame.find(ID));
  2695. }
  2696. }
  2697. }
  2698. else
  2699. {
  2700. if((rand()%50) == 0)
  2701. {
  2702. standingFrame.insert(std::make_pair(ID, 0));
  2703. }
  2704. }
  2705. }
  2706. creAnims[ID]->nextFrame(to, creAnims[ID]->pos.x, creAnims[ID]->pos.y, creDir[ID], animCount, incrementFrame, activeStack && ID==activeStack->ID, ID==mouseHoveredStack); //increment always when moving, never if stack died
  2707. //printing amount
  2708. if(stack->count > 0 //don't print if stack is not alive
  2709. && (!curInt->curAction
  2710. || (curInt->curAction->stackNumber != ID //don't print if stack is currently taking an action
  2711. && (curInt->curAction->actionType != BattleAction::WALK_AND_ATTACK || stack->position != curInt->curAction->additionalInfo) //nor if it's an object of attack
  2712. && (curInt->curAction->destinationTile != stack->position) //nor if it's on destination tile for current action
  2713. )
  2714. )
  2715. && !stack->hasBonusOfType(Bonus::SIEGE_WEAPON) //and not a war machine...
  2716. )
  2717. {
  2718. int xAdd = stack->attackerOwned ? 220 : 202;
  2719. //blitting amoutn background box
  2720. SDL_Surface *amountBG = NULL;
  2721. BonusList spellEffects = stack->getSpellBonuses();
  2722. if(!spellEffects.size())
  2723. {
  2724. amountBG = amountNormal;
  2725. }
  2726. else
  2727. {
  2728. int pos=0; //determining total positiveness of effects
  2729. std::vector<si32> spellIds = stack->activeSpells();
  2730. for(std::vector<si32>::const_iterator it = spellIds.begin(); it != spellIds.end(); it++)
  2731. {
  2732. pos += CGI->spellh->spells[ *it ]->positiveness;
  2733. }
  2734. if(pos > 0)
  2735. {
  2736. amountBG = amountPositive;
  2737. }
  2738. else if(pos < 0)
  2739. {
  2740. amountBG = amountNegative;
  2741. }
  2742. else
  2743. {
  2744. amountBG = amountEffNeutral;
  2745. }
  2746. }
  2747. SDL_BlitSurface(amountBG, NULL, to, &genRect(amountNormal->h, amountNormal->w, creAnims[ID]->pos.x + xAdd, creAnims[ID]->pos.y + 260));
  2748. //blitting amount
  2749. CSDL_Ext::printAtMiddle(
  2750. makeNumberShort(stack->count),
  2751. creAnims[ID]->pos.x + xAdd + 15,
  2752. creAnims[ID]->pos.y + 260 + 5,
  2753. FONT_TINY,
  2754. zwykly,
  2755. to
  2756. );
  2757. }
  2758. }
  2759. void CBattleInterface::showPieceOfWall(SDL_Surface * to, int hex, const std::vector<const CStack*> & stacks)
  2760. {
  2761. if(!siegeH)
  2762. return;
  2763. static const std::map<int, int> hexToPart = boost::assign::map_list_of(12, 8)(16, 1)(29, 7)(50, 2)(62, 12)(78, 6)(112, 10)(147, 5)(165, 11)(182, 3)(186, 0);
  2764. //additionally print bottom wall
  2765. if(hex == 182)
  2766. {
  2767. siegeH->printPartOfWall(to, 4);
  2768. }
  2769. std::map<int, int>::const_iterator it = hexToPart.find(hex);
  2770. if(it != hexToPart.end())
  2771. {
  2772. siegeH->printPartOfWall(to, it->second);
  2773. //print creature in turret
  2774. int posToSeek = -1;
  2775. switch(it->second)
  2776. {
  2777. case 3: //bottom turret
  2778. posToSeek = -3;
  2779. break;
  2780. case 8: //upper turret
  2781. posToSeek = -4;
  2782. break;
  2783. case 2: //keep
  2784. posToSeek = -2;
  2785. break;
  2786. }
  2787. if(posToSeek != -1)
  2788. {
  2789. const CStack *turret = NULL;
  2790. BOOST_FOREACH(const CStack *s, stacks)
  2791. {
  2792. if(s->position == posToSeek)
  2793. {
  2794. turret = s;
  2795. break;
  2796. }
  2797. }
  2798. if(turret)
  2799. {
  2800. showAliveStack(turret, to);
  2801. //blitting creature cover
  2802. switch(posToSeek)
  2803. {
  2804. case -3: //bottom turret
  2805. siegeH->printPartOfWall(to, 16);
  2806. break;
  2807. case -4: //upper turret
  2808. siegeH->printPartOfWall(to, 17);
  2809. break;
  2810. case -2: //keep
  2811. siegeH->printPartOfWall(to, 15);
  2812. break;
  2813. }
  2814. }
  2815. }
  2816. }
  2817. }
  2818. void CBattleInterface::redrawBackgroundWithHexes(const CStack * activeStack)
  2819. {
  2820. shadedHexes = curInt->cb->battleGetAvailableHexes(activeStack, true);
  2821. //preparating background graphic with hexes and shaded hexes
  2822. blitAt(background, 0, 0, backgroundWithHexes);
  2823. if(curInt->sysOpts.printCellBorders)
  2824. CSDL_Ext::blit8bppAlphaTo24bpp(cellBorders, NULL, backgroundWithHexes, NULL);
  2825. if(curInt->sysOpts.printStackRange)
  2826. {
  2827. for(size_t m=0; m<shadedHexes.size(); ++m) //rows
  2828. {
  2829. int i = shadedHexes[m]/BFIELD_WIDTH; //row
  2830. int j = shadedHexes[m]%BFIELD_WIDTH-1; //column
  2831. int x = 58 + (i%2==0 ? 22 : 0) + 44*j;
  2832. int y = 86 + 42 * i;
  2833. CSDL_Ext::blit8bppAlphaTo24bpp(cellShade, NULL, backgroundWithHexes, &genRect(cellShade->h, cellShade->w, x, y));
  2834. }
  2835. }
  2836. }
  2837. void CBattleInterface::printConsoleAttacked( const CStack * defender, int dmg, int killed, const CStack * attacker )
  2838. {
  2839. char tabh[200];
  2840. int end = sprintf(tabh, CGI->generaltexth->allTexts[attacker->count > 1 ? 377 : 376].c_str(),
  2841. (attacker->count > 1 ? attacker->getCreature()->namePl.c_str() : attacker->getCreature()->nameSing.c_str()),
  2842. dmg);
  2843. if(killed > 0)
  2844. {
  2845. if(killed > 1)
  2846. {
  2847. sprintf(tabh + end, CGI->generaltexth->allTexts[379].c_str(), killed, defender->getCreature()->namePl.c_str());
  2848. }
  2849. else //killed == 1
  2850. {
  2851. sprintf(tabh + end, CGI->generaltexth->allTexts[378].c_str(), defender->getCreature()->nameSing.c_str());
  2852. }
  2853. }
  2854. console->addText(std::string(tabh));
  2855. }
  2856. void CBattleInterface::projectileShowHelper(SDL_Surface * to)
  2857. {
  2858. if(to == NULL)
  2859. to = screen;
  2860. std::list< std::list<SProjectileInfo>::iterator > toBeDeleted;
  2861. for(std::list<SProjectileInfo>::iterator it=projectiles.begin(); it!=projectiles.end(); ++it)
  2862. {
  2863. if(it->animStartDelay>0)
  2864. {
  2865. --(it->animStartDelay);
  2866. continue;
  2867. }
  2868. SDL_Rect dst;
  2869. dst.h = idToProjectile[it->creID]->ourImages[it->frameNum].bitmap->h;
  2870. dst.w = idToProjectile[it->creID]->ourImages[it->frameNum].bitmap->w;
  2871. dst.x = it->x;
  2872. dst.y = it->y;
  2873. if(it->reverse)
  2874. {
  2875. SDL_Surface * rev = CSDL_Ext::rotate01(idToProjectile[it->creID]->ourImages[it->frameNum].bitmap);
  2876. CSDL_Ext::blit8bppAlphaTo24bpp(rev, NULL, to, &dst);
  2877. SDL_FreeSurface(rev);
  2878. }
  2879. else
  2880. {
  2881. CSDL_Ext::blit8bppAlphaTo24bpp(idToProjectile[it->creID]->ourImages[it->frameNum].bitmap, NULL, to, &dst);
  2882. }
  2883. //actualizing projectile
  2884. ++it->step;
  2885. if(it->step == it->lastStep)
  2886. {
  2887. toBeDeleted.insert(toBeDeleted.end(), it);
  2888. }
  2889. else
  2890. {
  2891. it->x += it->dx;
  2892. it->y += it->dy;
  2893. if(it->spin)
  2894. {
  2895. ++(it->frameNum);
  2896. it->frameNum %= idToProjectile[it->creID]->ourImages.size();
  2897. }
  2898. }
  2899. }
  2900. for(std::list< std::list<SProjectileInfo>::iterator >::iterator it = toBeDeleted.begin(); it!= toBeDeleted.end(); ++it)
  2901. {
  2902. projectiles.erase(*it);
  2903. }
  2904. }
  2905. void CBattleInterface::endAction(const BattleAction* action)
  2906. {
  2907. //if((action->actionType==2 || (action->actionType==6 && action->destinationTile!=cb->battleGetPos(action->stackNumber)))) //activating interface when move is finished
  2908. // {
  2909. // activate();
  2910. // }
  2911. if(action->actionType == BattleAction::HERO_SPELL)
  2912. {
  2913. if(action->side)
  2914. defendingHero->setPhase(0);
  2915. else
  2916. attackingHero->setPhase(0);
  2917. }
  2918. if(action->actionType == BattleAction::WALK && creAnims[action->stackNumber]->getType() != 2) //walk or walk & attack
  2919. {
  2920. const CStack * stack = curInt->cb->battleGetStackByID(action->stackNumber);
  2921. pendingAnims.push_back(std::make_pair(new CBattleMoveEnd(this, stack, action->destinationTile), false));
  2922. }
  2923. if(action->actionType == BattleAction::CATAPULT) //catapult
  2924. {
  2925. }
  2926. //check if we should reverse stacks
  2927. std::set<const CStack *> stacks;
  2928. stacks.insert(LOCPLINT->cb->battleGetStackByID(action->stackNumber));
  2929. stacks.insert(LOCPLINT->cb->battleGetStackByPos(action->destinationTile));
  2930. BOOST_FOREACH(const CStack *s, stacks)
  2931. {
  2932. if(s && creDir[s->ID] != bool(s->attackerOwned) && s->alive())
  2933. {
  2934. addNewAnim(new CReverseAnim(this, s, s->position, false));
  2935. }
  2936. }
  2937. queue->update();
  2938. }
  2939. void CBattleInterface::hideQueue()
  2940. {
  2941. curInt->sysOpts.showQueue = false;
  2942. queue->deactivate();
  2943. if(!queue->embedded)
  2944. {
  2945. moveBy(Point(0, -queue->pos.h / 2));
  2946. GH.totalRedraw();
  2947. }
  2948. }
  2949. void CBattleInterface::showQueue()
  2950. {
  2951. curInt->sysOpts.showQueue = true;
  2952. queue->activate();
  2953. if(!queue->embedded)
  2954. {
  2955. moveBy(Point(0, +queue->pos.h / 2));
  2956. GH.totalRedraw();
  2957. }
  2958. }
  2959. void CBattleInterface::startAction(const BattleAction* action)
  2960. {
  2961. if(action->actionType == BattleAction::END_TACTIC_PHASE)
  2962. {
  2963. menu = BitmapHandler::loadBitmap("CBAR.bmp");
  2964. graphics->blueToPlayersAdv(menu, curInt->playerID);
  2965. if(active)
  2966. {
  2967. tacticsMode = false;
  2968. btactEnd->deactivate();
  2969. btactNext->deactivate();
  2970. bConsoleDown->activate();
  2971. bConsoleUp->activate();
  2972. }
  2973. redraw();
  2974. return;
  2975. }
  2976. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  2977. if(stack)
  2978. {
  2979. queue->update();
  2980. }
  2981. else
  2982. {
  2983. assert(action->actionType == BattleAction::HERO_SPELL); //only cast spell is valid action without acting stack number
  2984. }
  2985. if(action->actionType == BattleAction::WALK
  2986. || (action->actionType == BattleAction::WALK_AND_ATTACK && action->destinationTile != stack->position))
  2987. {
  2988. moveStarted = true;
  2989. if(creAnims[action->stackNumber]->framesInGroup(CCreatureAnim::MOVE_START))
  2990. {
  2991. const CStack * stack = curInt->cb->battleGetStackByID(action->stackNumber);
  2992. pendingAnims.push_back(std::make_pair(new CBattleMoveStart(this, stack), false));
  2993. }
  2994. }
  2995. if(active)
  2996. deactivate();
  2997. char txt[400];
  2998. if(action->actionType == BattleAction::HERO_SPELL) //when hero casts spell
  2999. {
  3000. if(action->side)
  3001. defendingHero->setPhase(4);
  3002. else
  3003. attackingHero->setPhase(4);
  3004. return;
  3005. }
  3006. if(!stack)
  3007. {
  3008. tlog1<<"Something wrong with stackNumber in actionStarted. Stack number: "<<action->stackNumber<<std::endl;
  3009. return;
  3010. }
  3011. int txtid = 0;
  3012. switch(action->actionType)
  3013. {
  3014. case BattleAction::WAIT:
  3015. txtid = 136;
  3016. break;
  3017. case BattleAction::BAD_MORALE:
  3018. txtid = -34; //negative -> no separate singular/plural form
  3019. displayEffect(30,stack->position);
  3020. break;
  3021. }
  3022. if(txtid > 0 && stack->count != 1)
  3023. txtid++; //move to plural text
  3024. else if(txtid < 0)
  3025. txtid = -txtid;
  3026. if(txtid)
  3027. {
  3028. sprintf(txt, CGI->generaltexth->allTexts[txtid].c_str(), (stack->count != 1) ? stack->getCreature()->namePl.c_str() : stack->getCreature()->nameSing.c_str(), 0);
  3029. console->addText(txt);
  3030. }
  3031. //displaying heal animation
  3032. if (action->actionType == BattleAction::STACK_HEAL)
  3033. {
  3034. displayEffect(50, action->destinationTile);
  3035. }
  3036. }
  3037. void CBattleInterface::waitForAnims()
  3038. {
  3039. LOCPLINT->pim->unlock();
  3040. animsAreDisplayed.waitWhileTrue();
  3041. LOCPLINT->pim->lock();
  3042. }
  3043. void CBattleInterface::bEndTacticPhase()
  3044. {
  3045. BattleAction endt = BattleAction::makeEndOFTacticPhase(curInt->cb->battleGetMySide());
  3046. curInt->cb->battleMakeTacticAction(&endt);
  3047. btactEnd->block(true);
  3048. }
  3049. void CBattleInterface::bTacticNextStack()
  3050. {
  3051. TStacks stacksOfMine = curInt->cb->battleGetStacks(IBattleCallback::ONLY_MINE);
  3052. TStacks::iterator it = vstd::find(stacksOfMine, activeStack);
  3053. if(it != stacksOfMine.end() && ++it != stacksOfMine.end())
  3054. stackActivated(*it);
  3055. else
  3056. stackActivated(stacksOfMine.front());
  3057. }
  3058. void CBattleHero::show(SDL_Surface *to)
  3059. {
  3060. //animation of flag
  3061. if(flip)
  3062. {
  3063. CSDL_Ext::blit8bppAlphaTo24bpp(
  3064. flag->ourImages[flagAnim].bitmap,
  3065. NULL,
  3066. screen,
  3067. &genRect(
  3068. flag->ourImages[flagAnim].bitmap->h,
  3069. flag->ourImages[flagAnim].bitmap->w,
  3070. 62 + pos.x,
  3071. 39 + pos.y
  3072. )
  3073. );
  3074. }
  3075. else
  3076. {
  3077. CSDL_Ext::blit8bppAlphaTo24bpp(
  3078. flag->ourImages[flagAnim].bitmap,
  3079. NULL,
  3080. screen,
  3081. &genRect(
  3082. flag->ourImages[flagAnim].bitmap->h,
  3083. flag->ourImages[flagAnim].bitmap->w,
  3084. 71 + pos.x,
  3085. 39 + pos.y
  3086. )
  3087. );
  3088. }
  3089. ++flagAnimCount;
  3090. if(flagAnimCount%4==0)
  3091. {
  3092. ++flagAnim;
  3093. flagAnim %= flag->ourImages.size();
  3094. }
  3095. //animation of hero
  3096. int tick=-1;
  3097. for(int i=0; i<dh->ourImages.size(); ++i)
  3098. {
  3099. if(dh->ourImages[i].groupNumber==phase)
  3100. ++tick;
  3101. if(tick==image)
  3102. {
  3103. SDL_Rect posb = pos;
  3104. CSDL_Ext::blit8bppAlphaTo24bpp(dh->ourImages[i].bitmap, NULL, to, &posb);
  3105. if(phase != 4 || nextPhase != -1 || image < 4)
  3106. {
  3107. if(flagAnimCount%2==0)
  3108. {
  3109. ++image;
  3110. }
  3111. if(dh->ourImages[(i+1)%dh->ourImages.size()].groupNumber!=phase) //back to appropriate frame
  3112. {
  3113. image = 0;
  3114. }
  3115. }
  3116. if(phase == 4 && nextPhase != -1 && image == 7)
  3117. {
  3118. phase = nextPhase;
  3119. nextPhase = -1;
  3120. image = 0;
  3121. }
  3122. break;
  3123. }
  3124. }
  3125. }
  3126. void CBattleHero::activate()
  3127. {
  3128. activateLClick();
  3129. }
  3130. void CBattleHero::deactivate()
  3131. {
  3132. deactivateLClick();
  3133. }
  3134. void CBattleHero::setPhase(int newPhase)
  3135. {
  3136. if(phase != 4)
  3137. {
  3138. phase = newPhase;
  3139. image = 0;
  3140. }
  3141. else
  3142. {
  3143. nextPhase = newPhase;
  3144. }
  3145. }
  3146. void CBattleHero::clickLeft(tribool down, bool previousState)
  3147. {
  3148. if(myOwner->spellDestSelectMode) //we are casting a spell
  3149. return;
  3150. if(!down && myHero && myOwner->curInt->cb->battleCanCastSpell()) //check conditions
  3151. {
  3152. for(int it=0; it<BFIELD_SIZE; ++it) //do nothing when any hex is hovered - hero's animation overlaps battlefield
  3153. {
  3154. if(myOwner->bfield[it].hovered && myOwner->bfield[it].strictHovered)
  3155. return;
  3156. }
  3157. CCS->curh->changeGraphic(0,0);
  3158. CSpellWindow * spellWindow = new CSpellWindow(genRect(595, 620, (conf.cc.resx - 620)/2, (conf.cc.resy - 595)/2), myHero, myOwner->curInt);
  3159. GH.pushInt(spellWindow);
  3160. }
  3161. }
  3162. CBattleHero::CBattleHero(const std::string & defName, int phaseG, int imageG, bool flipG, unsigned char player, const CGHeroInstance * hero, const CBattleInterface * owner): flip(flipG), myHero(hero), myOwner(owner), phase(phaseG), nextPhase(-1), image(imageG), flagAnim(0), flagAnimCount(0)
  3163. {
  3164. dh = CDefHandler::giveDef( defName );
  3165. for(int i=0; i<dh->ourImages.size(); ++i) //transforming images
  3166. {
  3167. if(flip)
  3168. {
  3169. SDL_Surface * hlp = CSDL_Ext::rotate01(dh->ourImages[i].bitmap);
  3170. SDL_FreeSurface(dh->ourImages[i].bitmap);
  3171. dh->ourImages[i].bitmap = hlp;
  3172. }
  3173. CSDL_Ext::alphaTransform(dh->ourImages[i].bitmap);
  3174. }
  3175. if(flip)
  3176. flag = CDefHandler::giveDef("CMFLAGR.DEF");
  3177. else
  3178. flag = CDefHandler::giveDef("CMFLAGL.DEF");
  3179. //coloring flag and adding transparency
  3180. for(int i=0; i<flag->ourImages.size(); ++i)
  3181. {
  3182. CSDL_Ext::alphaTransform(flag->ourImages[i].bitmap);
  3183. graphics->blueToPlayersAdv(flag->ourImages[i].bitmap, player);
  3184. }
  3185. }
  3186. CBattleHero::~CBattleHero()
  3187. {
  3188. delete dh;
  3189. delete flag;
  3190. }
  3191. Point CBattleHex::getXYUnitAnim(const int & hexNum, const bool & attacker, const CStack * stack, const CBattleInterface * cbi)
  3192. {
  3193. Point ret(-500, -500); //returned value
  3194. if(stack->position < 0) //creatures in turrets
  3195. {
  3196. const CCreature & turretCreature = *CGI->creh->creatures[ CGI->creh->factionToTurretCreature[cbi->siegeH->town->town->typeID] ];
  3197. int xShift = turretCreature.isDoubleWide() ? 44 : 0;
  3198. switch(stack->position)
  3199. {
  3200. case -2: //keep
  3201. ret = Point(505 + xShift, -66);
  3202. break;
  3203. case -3: //lower turret
  3204. ret = Point(368 + xShift, 304);
  3205. break;
  3206. case -4: //upper turret
  3207. ret = Point(339 + xShift, -192);
  3208. break;
  3209. }
  3210. }
  3211. else
  3212. {
  3213. ret.y = -139 + 42 * (hexNum/BFIELD_WIDTH); //counting y
  3214. //counting x
  3215. if(attacker)
  3216. {
  3217. ret.x = -160 + 22 * ( ((hexNum/BFIELD_WIDTH) + 1)%2 ) + 44 * (hexNum % BFIELD_WIDTH);
  3218. }
  3219. else
  3220. {
  3221. ret.x = -219 + 22 * ( ((hexNum/BFIELD_WIDTH) + 1)%2 ) + 44 * (hexNum % BFIELD_WIDTH);
  3222. }
  3223. //shifting position for double - hex creatures
  3224. if(stack && stack->doubleWide())
  3225. {
  3226. if(attacker)
  3227. {
  3228. ret.x -= 42;
  3229. }
  3230. else
  3231. {
  3232. ret.x += 42;
  3233. }
  3234. }
  3235. }
  3236. //returning
  3237. return ret +CPlayerInterface::battleInt->pos;
  3238. }
  3239. void CBattleHex::activate()
  3240. {
  3241. activateHover();
  3242. activateMouseMove();
  3243. activateLClick();
  3244. activateRClick();
  3245. }
  3246. void CBattleHex::deactivate()
  3247. {
  3248. deactivateHover();
  3249. deactivateMouseMove();
  3250. deactivateLClick();
  3251. deactivateRClick();
  3252. }
  3253. void CBattleHex::hover(bool on)
  3254. {
  3255. hovered = on;
  3256. //Hoverable::hover(on);
  3257. if(!on && setAlterText)
  3258. {
  3259. myInterface->console->alterTxt = std::string();
  3260. setAlterText = false;
  3261. }
  3262. }
  3263. CBattleHex::CBattleHex() : setAlterText(false), myNumber(-1), accessible(true), hovered(false), strictHovered(false), myInterface(NULL)
  3264. {
  3265. }
  3266. void CBattleHex::mouseMoved(const SDL_MouseMotionEvent &sEvent)
  3267. {
  3268. if(myInterface->cellShade)
  3269. {
  3270. if(CSDL_Ext::SDL_GetPixel(myInterface->cellShade, sEvent.x-pos.x, sEvent.y-pos.y) == 0) //hovered pixel is outside hex
  3271. {
  3272. strictHovered = false;
  3273. }
  3274. else //hovered pixel is inside hex
  3275. {
  3276. strictHovered = true;
  3277. }
  3278. }
  3279. if(hovered && strictHovered) //print attacked creature to console
  3280. {
  3281. const CStack * attackedStack = myInterface->curInt->cb->battleGetStackByPos(myNumber);
  3282. if(myInterface->console->alterTxt.size() == 0 &&attackedStack != NULL &&
  3283. attackedStack->owner != myInterface->curInt->playerID &&
  3284. attackedStack->alive())
  3285. {
  3286. char tabh[160];
  3287. const std::string & attackedName = attackedStack->count == 1 ? attackedStack->getCreature()->nameSing : attackedStack->getCreature()->namePl;
  3288. sprintf(tabh, CGI->generaltexth->allTexts[220].c_str(), attackedName.c_str());
  3289. myInterface->console->alterTxt = std::string(tabh);
  3290. setAlterText = true;
  3291. }
  3292. }
  3293. else if(setAlterText)
  3294. {
  3295. myInterface->console->alterTxt = std::string();
  3296. setAlterText = false;
  3297. }
  3298. }
  3299. void CBattleHex::clickLeft(tribool down, bool previousState)
  3300. {
  3301. if(!down && hovered && strictHovered) //we've been really clicked!
  3302. {
  3303. myInterface->hexLclicked(myNumber);
  3304. }
  3305. }
  3306. void CBattleHex::clickRight(tribool down, bool previousState)
  3307. {
  3308. const CStack * myst = myInterface->curInt->cb->battleGetStackByPos(myNumber); //stack info
  3309. if(hovered && strictHovered && myst!=NULL)
  3310. {
  3311. if(!myst->alive()) return;
  3312. if(down)
  3313. {
  3314. GH.pushInt(new CCreInfoWindow(*myst));
  3315. }
  3316. }
  3317. }
  3318. CBattleConsole::CBattleConsole() : lastShown(-1), alterTxt(""), whoSetAlter(0)
  3319. {
  3320. }
  3321. CBattleConsole::~CBattleConsole()
  3322. {
  3323. texts.clear();
  3324. }
  3325. void CBattleConsole::show(SDL_Surface * to)
  3326. {
  3327. if(ingcAlter.size())
  3328. {
  3329. CSDL_Ext::printAtMiddleWB(ingcAlter, pos.x + pos.w/2, pos.y + 11, FONT_SMALL, 80, zwykly, to);
  3330. }
  3331. else if(alterTxt.size())
  3332. {
  3333. CSDL_Ext::printAtMiddleWB(alterTxt, pos.x + pos.w/2, pos.y + 11, FONT_SMALL, 80, zwykly, to);
  3334. }
  3335. else if(texts.size())
  3336. {
  3337. if(texts.size()==1)
  3338. {
  3339. CSDL_Ext::printAtMiddleWB(texts[0], pos.x + pos.w/2, pos.y + 11, FONT_SMALL, 80, zwykly, to);
  3340. }
  3341. else
  3342. {
  3343. CSDL_Ext::printAtMiddleWB(texts[lastShown-1], pos.x + pos.w/2, pos.y + 11, FONT_SMALL, 80, zwykly, to);
  3344. CSDL_Ext::printAtMiddleWB(texts[lastShown], pos.x + pos.w/2, pos.y + 27, FONT_SMALL, 80, zwykly, to);
  3345. }
  3346. }
  3347. }
  3348. bool CBattleConsole::addText(const std::string & text)
  3349. {
  3350. if(text.size()>70)
  3351. return false; //text too long!
  3352. int firstInToken = 0;
  3353. for(int i=0; i<text.size(); ++i) //tokenize
  3354. {
  3355. if(text[i] == 10)
  3356. {
  3357. texts.push_back( text.substr(firstInToken, i-firstInToken) );
  3358. firstInToken = i+1;
  3359. }
  3360. }
  3361. texts.push_back( text.substr(firstInToken, text.size()) );
  3362. lastShown = texts.size()-1;
  3363. return true;
  3364. }
  3365. void CBattleConsole::eraseText(unsigned int pos)
  3366. {
  3367. if(pos < texts.size())
  3368. {
  3369. texts.erase(texts.begin() + pos);
  3370. if(lastShown == texts.size())
  3371. --lastShown;
  3372. }
  3373. }
  3374. void CBattleConsole::changeTextAt(const std::string & text, unsigned int pos)
  3375. {
  3376. if(pos >= texts.size()) //no such pos
  3377. return;
  3378. texts[pos] = text;
  3379. }
  3380. void CBattleConsole::scrollUp(unsigned int by)
  3381. {
  3382. if(lastShown > by)
  3383. lastShown -= by;
  3384. }
  3385. void CBattleConsole::scrollDown(unsigned int by)
  3386. {
  3387. if(lastShown + by < texts.size())
  3388. lastShown += by;
  3389. }
  3390. CBattleResultWindow::CBattleResultWindow(const BattleResult &br, const SDL_Rect & pos, CBattleInterface * _owner)
  3391. : owner(_owner)
  3392. {
  3393. this->pos = pos;
  3394. background = BitmapHandler::loadBitmap("CPRESULT.BMP", true);
  3395. graphics->blueToPlayersAdv(background, owner->curInt->playerID);
  3396. SDL_Surface * pom = SDL_ConvertSurface(background, screen->format, screen->flags);
  3397. SDL_FreeSurface(background);
  3398. background = pom;
  3399. exit = new AdventureMapButton (std::string(), std::string(), boost::bind(&CBattleResultWindow::bExitf,this), 384 + pos.x, 505 + pos.y, "iok6432.def", SDLK_RETURN);
  3400. if(br.winner==0) //attacker won
  3401. {
  3402. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[410], 59, 124, FONT_SMALL, zwykly, background);
  3403. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[411], 408, 124, FONT_SMALL, zwykly, background);
  3404. }
  3405. else //if(br.winner==1)
  3406. {
  3407. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[411], 59, 124, FONT_SMALL, zwykly, background);
  3408. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[410], 412, 124, FONT_SMALL, zwykly, background);
  3409. }
  3410. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[407], 232, 302, FONT_BIG, tytulowy, background);
  3411. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[408], 232, 332, FONT_BIG, zwykly, background);
  3412. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[409], 237, 428, FONT_BIG, zwykly, background);
  3413. std::string attackerName, defenderName;
  3414. if(owner->attackingHeroInstance) //a hero attacked
  3415. {
  3416. SDL_BlitSurface(graphics->portraitLarge[owner->attackingHeroInstance->portrait], NULL, background, &genRect(64, 58, 21, 38));
  3417. //setting attackerName
  3418. attackerName = owner->attackingHeroInstance->name;
  3419. }
  3420. else //a monster attacked
  3421. {
  3422. int bestMonsterID = -1;
  3423. int bestPower = 0;
  3424. for(TSlots::const_iterator it = owner->army1->Slots().begin(); it!=owner->army1->Slots().end(); ++it)
  3425. {
  3426. if( it->second->type->AIValue > bestPower)
  3427. {
  3428. bestPower = it->second->type->AIValue;
  3429. bestMonsterID = it->second->type->idNumber;
  3430. }
  3431. }
  3432. SDL_BlitSurface(graphics->bigImgs[bestMonsterID], NULL, background, &genRect(64, 58, 21, 38));
  3433. //setting attackerName
  3434. attackerName = CGI->creh->creatures[bestMonsterID]->namePl;
  3435. }
  3436. if(owner->defendingHeroInstance) //a hero defended
  3437. {
  3438. SDL_BlitSurface(graphics->portraitLarge[owner->defendingHeroInstance->portrait], NULL, background, &genRect(64, 58, 392, 38));
  3439. //setting defenderName
  3440. defenderName = owner->defendingHeroInstance->name;
  3441. }
  3442. else //a monster defended
  3443. {
  3444. int bestMonsterID = -1;
  3445. int bestPower = 0;
  3446. for(TSlots::const_iterator it = owner->army2->Slots().begin(); it!=owner->army2->Slots().end(); ++it)
  3447. {
  3448. if( it->second->type->AIValue > bestPower)
  3449. {
  3450. bestPower = it->second->type->AIValue;
  3451. bestMonsterID = it->second->type->idNumber;
  3452. }
  3453. }
  3454. SDL_BlitSurface(graphics->bigImgs[bestMonsterID], NULL, background, &genRect(64, 58, 392, 38));
  3455. //setting defenderName
  3456. defenderName = CGI->creh->creatures[bestMonsterID]->namePl;
  3457. }
  3458. //printing attacker and defender's names
  3459. CSDL_Ext::printAt(attackerName, 89, 37, FONT_SMALL, zwykly, background);
  3460. CSDL_Ext::printTo(defenderName, 381, 53, FONT_SMALL, zwykly, background);
  3461. //printing casualities
  3462. for(int step = 0; step < 2; ++step)
  3463. {
  3464. if(br.casualties[step].size()==0)
  3465. {
  3466. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[523], 235, 360 + 97*step, FONT_SMALL, zwykly, background);
  3467. }
  3468. else
  3469. {
  3470. int xPos = 235 - (br.casualties[step].size()*32 + (br.casualties[step].size() - 1)*10)/2; //increment by 42 with each picture
  3471. int yPos = 344 + step*97;
  3472. for(std::map<ui32,si32>::const_iterator it=br.casualties[step].begin(); it!=br.casualties[step].end(); ++it)
  3473. {
  3474. blitAt(graphics->smallImgs[it->first], xPos, yPos, background);
  3475. std::ostringstream amount;
  3476. amount<<it->second;
  3477. CSDL_Ext::printAtMiddle(amount.str(), xPos+16, yPos + 42, FONT_SMALL, zwykly, background);
  3478. xPos += 42;
  3479. }
  3480. }
  3481. }
  3482. //printing result description
  3483. bool weAreAttacker = (owner->curInt->playerID == owner->attackingHeroInstance->tempOwner);
  3484. if((br.winner == 0 && weAreAttacker) || (br.winner == 1 && !weAreAttacker)) //we've won
  3485. {
  3486. int text=-1;
  3487. switch(br.result)
  3488. {
  3489. case 0: text = 304; break;
  3490. case 1: text = 303; break;
  3491. case 2: text = 302; break;
  3492. }
  3493. CCS->musich->playMusic(musicBase::winBattle);
  3494. #ifdef _WIN32
  3495. CCS->videoh->open(VIDEO_WIN);
  3496. #else
  3497. CCS->videoh->open(VIDEO_WIN, true);
  3498. #endif
  3499. std::string str = CGI->generaltexth->allTexts[text];
  3500. const CGHeroInstance * ourHero = weAreAttacker? owner->attackingHeroInstance : owner->defendingHeroInstance;
  3501. if (ourHero)
  3502. {
  3503. str += CGI->generaltexth->allTexts[305];
  3504. boost::algorithm::replace_first(str,"%s",ourHero->name);
  3505. boost::algorithm::replace_first(str,"%d",boost::lexical_cast<std::string>(br.exp[weAreAttacker?0:1]));
  3506. }
  3507. CSDL_Ext::printAtMiddleWB(str, 235, 235, FONT_SMALL, 55, zwykly, background);
  3508. }
  3509. else // we lose
  3510. {
  3511. switch(br.result)
  3512. {
  3513. case 0: //normal victory
  3514. {
  3515. CCS->musich->playMusic(musicBase::loseCombat);
  3516. CCS->videoh->open(VIDEO_LOSE_BATTLE_START);
  3517. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[311], 235, 235, FONT_SMALL, zwykly, background);
  3518. break;
  3519. }
  3520. case 1: //flee
  3521. {
  3522. CCS->musich->playMusic(musicBase::retreatBattle);
  3523. CCS->videoh->open(VIDEO_RETREAT_START);
  3524. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[310], 235, 235, FONT_SMALL, zwykly, background);
  3525. break;
  3526. }
  3527. case 2: //surrender
  3528. {
  3529. CCS->musich->playMusic(musicBase::surrenderBattle);
  3530. CCS->videoh->open(VIDEO_SURRENDER);
  3531. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[309], 235, 220, FONT_SMALL, zwykly, background);
  3532. break;
  3533. }
  3534. }
  3535. }
  3536. }
  3537. CBattleResultWindow::~CBattleResultWindow()
  3538. {
  3539. SDL_FreeSurface(background);
  3540. }
  3541. void CBattleResultWindow::activate()
  3542. {
  3543. owner->curInt->showingDialog->set(true);
  3544. exit->activate();
  3545. }
  3546. void CBattleResultWindow::deactivate()
  3547. {
  3548. exit->deactivate();
  3549. }
  3550. void CBattleResultWindow::show(SDL_Surface *to)
  3551. {
  3552. //evaluating to
  3553. if(!to)
  3554. to = screen;
  3555. CCS->videoh->update(107, 70, background, false, true);
  3556. SDL_BlitSurface(background, NULL, to, &pos);
  3557. exit->showAll(to);
  3558. }
  3559. void CBattleResultWindow::bExitf()
  3560. {
  3561. if(LOCPLINT->cb->getStartInfo()->mode == StartInfo::DUEL)
  3562. {
  3563. std::exit(0);
  3564. }
  3565. CPlayerInterface * intTmp = owner->curInt;
  3566. GH.popInts(2); //first - we; second - battle interface
  3567. intTmp->showingDialog->setn(false);
  3568. CCS->videoh->close();
  3569. }
  3570. CBattleOptionsWindow::CBattleOptionsWindow(const SDL_Rect & position, CBattleInterface *owner): myInt(owner)
  3571. {
  3572. pos = position;
  3573. SDL_Surface *hhlp = BitmapHandler::loadBitmap("comopbck.bmp", true);
  3574. graphics->blueToPlayersAdv(hhlp, owner->curInt->playerID);
  3575. background = SDL_ConvertSurface(hhlp, screen->format, 0);
  3576. SDL_SetColorKey(background, SDL_SRCCOLORKEY, SDL_MapRGB(background->format,0,255,255));
  3577. SDL_FreeSurface(hhlp);
  3578. viewGrid = new CHighlightableButton(boost::bind(&CBattleInterface::setPrintCellBorders, owner, true), boost::bind(&CBattleInterface::setPrintCellBorders, owner, false), boost::assign::map_list_of(0,CGI->generaltexth->zelp[427].first)(3,CGI->generaltexth->zelp[427].first), CGI->generaltexth->zelp[427].second, false, "sysopchk.def", NULL, 185, 140, false);
  3579. viewGrid->select(owner->curInt->sysOpts.printCellBorders);
  3580. movementShadow = new CHighlightableButton(boost::bind(&CBattleInterface::setPrintStackRange, owner, true), boost::bind(&CBattleInterface::setPrintStackRange, owner, false), boost::assign::map_list_of(0,CGI->generaltexth->zelp[428].first)(3,CGI->generaltexth->zelp[428].first), CGI->generaltexth->zelp[428].second, false, "sysopchk.def", NULL, 185, 173, false);
  3581. movementShadow->select(owner->curInt->sysOpts.printStackRange);
  3582. mouseShadow = new CHighlightableButton(boost::bind(&CBattleInterface::setPrintMouseShadow, owner, true), boost::bind(&CBattleInterface::setPrintMouseShadow, owner, false), boost::assign::map_list_of(0,CGI->generaltexth->zelp[429].first)(3,CGI->generaltexth->zelp[429].first), CGI->generaltexth->zelp[429].second, false, "sysopchk.def", NULL, 185, 207, false);
  3583. mouseShadow->select(owner->curInt->sysOpts.printMouseShadow);
  3584. animSpeeds = new CHighlightableButtonsGroup(0);
  3585. animSpeeds->addButton(boost::assign::map_list_of(0,CGI->generaltexth->zelp[422].first),CGI->generaltexth->zelp[422].second, "sysopb9.def",188, 309, 1);
  3586. animSpeeds->addButton(boost::assign::map_list_of(0,CGI->generaltexth->zelp[423].first),CGI->generaltexth->zelp[423].second, "sysob10.def",252, 309, 2);
  3587. animSpeeds->addButton(boost::assign::map_list_of(0,CGI->generaltexth->zelp[424].first),CGI->generaltexth->zelp[424].second, "sysob11.def",315, 309, 4);
  3588. animSpeeds->select(owner->getAnimSpeed(), 1);
  3589. animSpeeds->onChange = boost::bind(&CBattleInterface::setAnimSpeed, owner, _1);
  3590. setToDefault = new AdventureMapButton (CGI->generaltexth->zelp[392].first, CGI->generaltexth->zelp[392].second, boost::bind(&CBattleOptionsWindow::bDefaultf,this), 405, 443, "codefaul.def");
  3591. setToDefault->swappedImages = true;
  3592. setToDefault->update();
  3593. exit = new AdventureMapButton (CGI->generaltexth->zelp[393].first, CGI->generaltexth->zelp[393].second, boost::bind(&CBattleOptionsWindow::bExitf,this), 516, 443, "soretrn.def",SDLK_RETURN);
  3594. exit->swappedImages = true;
  3595. exit->update();
  3596. //printing texts to background
  3597. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[392], 242, 32, FONT_BIG, tytulowy, background); //window title
  3598. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[393], 122, 214, FONT_MEDIUM, tytulowy, background); //animation speed
  3599. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[394], 122, 293, FONT_MEDIUM, tytulowy, background); //music volume
  3600. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[395], 122, 359, FONT_MEDIUM, tytulowy, background); //effects' volume
  3601. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[396], 353, 66, FONT_MEDIUM, tytulowy, background); //auto - combat options
  3602. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[397], 353, 265, FONT_MEDIUM, tytulowy, background); //creature info
  3603. //auto - combat options
  3604. CSDL_Ext::printAt(CGI->generaltexth->allTexts[398], 283, 86, FONT_MEDIUM, zwykly, background); //creatures
  3605. CSDL_Ext::printAt(CGI->generaltexth->allTexts[399], 283, 116, FONT_MEDIUM, zwykly, background); //spells
  3606. CSDL_Ext::printAt(CGI->generaltexth->allTexts[400], 283, 146, FONT_MEDIUM, zwykly, background); //catapult
  3607. CSDL_Ext::printAt(CGI->generaltexth->allTexts[151], 283, 176, FONT_MEDIUM, zwykly, background); //ballista
  3608. CSDL_Ext::printAt(CGI->generaltexth->allTexts[401], 283, 206, FONT_MEDIUM, zwykly, background); //first aid tent
  3609. //creature info
  3610. CSDL_Ext::printAt(CGI->generaltexth->allTexts[402], 283, 285, FONT_MEDIUM, zwykly, background); //all stats
  3611. CSDL_Ext::printAt(CGI->generaltexth->allTexts[403], 283, 315, FONT_MEDIUM, zwykly, background); //spells only
  3612. //general options
  3613. CSDL_Ext::printAt(CGI->generaltexth->allTexts[404], 61, 57, FONT_MEDIUM, zwykly, background); //hex grid
  3614. CSDL_Ext::printAt(CGI->generaltexth->allTexts[405], 61, 90, FONT_MEDIUM, zwykly, background); //movement shadow
  3615. CSDL_Ext::printAt(CGI->generaltexth->allTexts[406], 61, 124, FONT_MEDIUM, zwykly, background); //cursor shadow
  3616. CSDL_Ext::printAt(CGI->generaltexth->allTexts[577], 61, 156, FONT_MEDIUM, zwykly, background); //spellbook animation
  3617. //texts printed
  3618. }
  3619. CBattleOptionsWindow::~CBattleOptionsWindow()
  3620. {
  3621. SDL_FreeSurface(background);
  3622. delete setToDefault;
  3623. delete exit;
  3624. delete viewGrid;
  3625. delete movementShadow;
  3626. delete animSpeeds;
  3627. delete mouseShadow;
  3628. }
  3629. void CBattleOptionsWindow::activate()
  3630. {
  3631. setToDefault->activate();
  3632. exit->activate();
  3633. viewGrid->activate();
  3634. movementShadow->activate();
  3635. animSpeeds->activate();
  3636. mouseShadow->activate();
  3637. }
  3638. void CBattleOptionsWindow::deactivate()
  3639. {
  3640. setToDefault->deactivate();
  3641. exit->deactivate();
  3642. viewGrid->deactivate();
  3643. movementShadow->deactivate();
  3644. animSpeeds->deactivate();
  3645. mouseShadow->deactivate();
  3646. }
  3647. void CBattleOptionsWindow::show(SDL_Surface *to)
  3648. {
  3649. if(!to) //"evaluating" to
  3650. to = screen;
  3651. SDL_BlitSurface(background, NULL, to, &pos);
  3652. setToDefault->showAll(to);
  3653. exit->showAll(to);
  3654. viewGrid->showAll(to);
  3655. movementShadow->showAll(to);
  3656. animSpeeds->showAll(to);
  3657. mouseShadow->showAll(to);
  3658. }
  3659. void CBattleOptionsWindow::bDefaultf()
  3660. {
  3661. }
  3662. void CBattleOptionsWindow::bExitf()
  3663. {
  3664. GH.popIntTotally(this);
  3665. }
  3666. std::string CBattleInterface::SiegeHelper::townTypeInfixes[F_NUMBER] = {"CS", "RM", "TW", "IN", "NC", "DN", "ST", "FR", "EL"};
  3667. CBattleInterface::SiegeHelper::SiegeHelper(const CGTownInstance *siegeTown, const CBattleInterface * _owner)
  3668. : owner(_owner), town(siegeTown)
  3669. {
  3670. for(int g=0; g<ARRAY_COUNT(walls); ++g)
  3671. {
  3672. walls[g] = BitmapHandler::loadBitmap( getSiegeName(g) );
  3673. }
  3674. }
  3675. CBattleInterface::SiegeHelper::~SiegeHelper()
  3676. {
  3677. for(int g=0; g<ARRAY_COUNT(walls); ++g)
  3678. {
  3679. SDL_FreeSurface(walls[g]);
  3680. }
  3681. }
  3682. std::string CBattleInterface::SiegeHelper::getSiegeName(ui16 what, ui16 additInfo) const
  3683. {
  3684. if(what == 2 || what == 3 || what == 8)
  3685. {
  3686. if(additInfo == 3) additInfo = 2;
  3687. }
  3688. char buf[100];
  3689. SDL_itoa(additInfo, buf, 10);
  3690. std::string addit(buf);
  3691. switch(what)
  3692. {
  3693. case 0: //background
  3694. return "SG" + townTypeInfixes[town->town->typeID] + "BACK.BMP";
  3695. case 1: //background wall
  3696. {
  3697. switch(town->town->typeID)
  3698. {
  3699. case 5: case 4: case 1: case 6:
  3700. return "SG" + townTypeInfixes[town->town->typeID] + "TPW1.BMP";
  3701. case 0: case 2: case 3: case 7: case 8:
  3702. return "SG" + townTypeInfixes[town->town->typeID] + "TPWL.BMP";
  3703. default:
  3704. return "";
  3705. }
  3706. }
  3707. case 2: //keep
  3708. return "SG" + townTypeInfixes[town->town->typeID] + "MAN" + addit + ".BMP";
  3709. case 3: //bottom tower
  3710. return "SG" + townTypeInfixes[town->town->typeID] + "TW1" + addit + ".BMP";
  3711. case 4: //bottom wall
  3712. return "SG" + townTypeInfixes[town->town->typeID] + "WA1" + addit + ".BMP";
  3713. case 5: //below gate
  3714. return "SG" + townTypeInfixes[town->town->typeID] + "WA3" + addit + ".BMP";
  3715. case 6: //over gate
  3716. return "SG" + townTypeInfixes[town->town->typeID] + "WA4" + addit + ".BMP";
  3717. case 7: //upper wall
  3718. return "SG" + townTypeInfixes[town->town->typeID] + "WA6" + addit + ".BMP";
  3719. case 8: //upper tower
  3720. return "SG" + townTypeInfixes[town->town->typeID] + "TW2" + addit + ".BMP";
  3721. case 9: //gate
  3722. return "SG" + townTypeInfixes[town->town->typeID] + "DRW" + addit + ".BMP";
  3723. case 10: //gate arch
  3724. return "SG" + townTypeInfixes[town->town->typeID] + "ARCH.BMP";
  3725. case 11: //bottom static wall
  3726. return "SG" + townTypeInfixes[town->town->typeID] + "WA2.BMP";
  3727. case 12: //upper static wall
  3728. return "SG" + townTypeInfixes[town->town->typeID] + "WA5.BMP";
  3729. case 13: //moat
  3730. return "SG" + townTypeInfixes[town->town->typeID] + "MOAT.BMP";
  3731. case 14: //mlip
  3732. return "SG" + townTypeInfixes[town->town->typeID] + "MLIP.BMP";
  3733. case 15: //keep creature cover
  3734. return "SG" + townTypeInfixes[town->town->typeID] + "MANC.BMP";
  3735. case 16: //bottom turret creature cover
  3736. return "SG" + townTypeInfixes[town->town->typeID] + "TW1C.BMP";
  3737. case 17: //upper turret creature cover
  3738. return "SG" + townTypeInfixes[town->town->typeID] + "TW2C.BMP";
  3739. default:
  3740. return "";
  3741. }
  3742. }
  3743. void CBattleInterface::SiegeHelper::printPartOfWall(SDL_Surface * to, int what)
  3744. {
  3745. Point pos = Point(-1, -1);
  3746. switch(what)
  3747. {
  3748. case 1: //background wall
  3749. pos = Point(owner->pos.w + owner->pos.x - walls[1]->w, 55 + owner->pos.y);
  3750. break;
  3751. case 2: //keep
  3752. pos = Point(owner->pos.w + owner->pos.x - walls[2]->w, 154 + owner->pos.y);
  3753. break;
  3754. case 3: //bottom tower
  3755. case 4: //bottom wall
  3756. case 5: //below gate
  3757. case 6: //over gate
  3758. case 7: //upper wall
  3759. case 8: //upper tower
  3760. case 9: //gate
  3761. case 10: //gate arch
  3762. case 11: //bottom static wall
  3763. case 12: //upper static wall
  3764. pos.x = graphics->wallPositions[town->town->typeID][what - 3].x + owner->pos.x;
  3765. pos.y = graphics->wallPositions[town->town->typeID][what - 3].y + owner->pos.y;
  3766. break;
  3767. case 15: //keep creature cover
  3768. pos = Point(owner->pos.w + owner->pos.x - walls[2]->w, 154 + owner->pos.y);
  3769. break;
  3770. case 16: //bottom turret creature cover
  3771. pos.x = graphics->wallPositions[town->town->typeID][0].x + owner->pos.x;
  3772. pos.y = graphics->wallPositions[town->town->typeID][0].y + owner->pos.y;
  3773. break;
  3774. case 17: //upper turret creature cover
  3775. pos.x = graphics->wallPositions[town->town->typeID][5].x + owner->pos.x;
  3776. pos.y = graphics->wallPositions[town->town->typeID][5].y + owner->pos.y;
  3777. break;
  3778. };
  3779. if(pos.x != -1)
  3780. {
  3781. blitAt(walls[what], pos.x, pos.y, to);
  3782. }
  3783. }
  3784. void CStackQueue::update()
  3785. {
  3786. stacksSorted.clear();
  3787. owner->curInt->cb->getStackQueue(stacksSorted, QUEUE_SIZE);
  3788. for (int i = 0; i < QUEUE_SIZE ; i++)
  3789. {
  3790. stackBoxes[i]->setStack(stacksSorted[i]);
  3791. }
  3792. }
  3793. CStackQueue::CStackQueue(bool Embedded, CBattleInterface * _owner)
  3794. :embedded(Embedded), owner(_owner)
  3795. {
  3796. OBJ_CONSTRUCTION_CAPTURING_ALL;
  3797. if(embedded)
  3798. {
  3799. box = NULL;
  3800. bg = NULL;
  3801. pos.w = QUEUE_SIZE * 37;
  3802. pos.h = 32; //height of small creature img
  3803. pos.x = screen->w/2 - pos.w/2;
  3804. pos.y = (screen->h - 600)/2 + 10;
  3805. }
  3806. else
  3807. {
  3808. box = BitmapHandler::loadBitmap("CHRROP.pcx");
  3809. bg = BitmapHandler::loadBitmap("DIBOXPI.pcx");
  3810. pos.w = 600;
  3811. pos.h = bg->h;
  3812. }
  3813. stackBoxes.resize(QUEUE_SIZE);
  3814. for (int i = 0; i < QUEUE_SIZE; i++)
  3815. {
  3816. stackBoxes[i] = new StackBox(box);
  3817. stackBoxes[i]->pos.x += 6 + (embedded ? 37 : 79)*i;
  3818. }
  3819. }
  3820. CStackQueue::~CStackQueue()
  3821. {
  3822. SDL_FreeSurface(box);
  3823. }
  3824. void CStackQueue::showAll( SDL_Surface *to )
  3825. {
  3826. blitBg(to);
  3827. CIntObject::showAll(to);
  3828. }
  3829. void CStackQueue::blitBg( SDL_Surface * to )
  3830. {
  3831. if(bg)
  3832. {
  3833. for (int w = 0; w < pos.w; w += bg->w)
  3834. {
  3835. blitAtLoc(bg, w, 0, to);
  3836. }
  3837. }
  3838. }
  3839. void CStackQueue::StackBox::showAll( SDL_Surface *to )
  3840. {
  3841. assert(my);
  3842. if(bg)
  3843. {
  3844. graphics->blueToPlayersAdv(bg, my->owner);
  3845. //SDL_UpdateRect(bg, 0, 0, 0, 0);
  3846. CSDL_Ext::blit8bppAlphaTo24bpp(bg, NULL, to, &genRect(bg->h, bg->w, pos.x, pos.y));
  3847. //blitAt(bg, pos, to);
  3848. blitAt(graphics->bigImgs[my->getCreature()->idNumber], pos.x +9, pos.y + 1, to);
  3849. printAtMiddleLoc(makeNumberShort(my->count), pos.w/2, pos.h - 12, FONT_MEDIUM, zwykly, to);
  3850. }
  3851. else
  3852. {
  3853. blitAt(graphics->smallImgs[-2], pos, to);
  3854. blitAt(graphics->smallImgs[my->getCreature()->idNumber], pos, to);
  3855. const SDL_Color &ownerColor = (my->owner == 255 ? *graphics->neutralColor : graphics->playerColors[my->owner]);
  3856. CSDL_Ext::drawBorder(to, pos, int3(ownerColor.r, ownerColor.g, ownerColor.b));
  3857. printAtMiddleLoc(makeNumberShort(my->count), pos.w/2, pos.h - 8, FONT_TINY, zwykly, to);
  3858. }
  3859. }
  3860. void CStackQueue::StackBox::setStack( const CStack *nStack )
  3861. {
  3862. my = nStack;
  3863. }
  3864. CStackQueue::StackBox::StackBox(SDL_Surface *BG)
  3865. :my(NULL), bg(BG)
  3866. {
  3867. if(bg)
  3868. {
  3869. pos.w = bg->w;
  3870. pos.h = bg->h;
  3871. }
  3872. else
  3873. {
  3874. pos.w = pos.h = 32;
  3875. }
  3876. pos.y += 2;
  3877. }
  3878. CStackQueue::StackBox::~StackBox()
  3879. {
  3880. }
  3881. void CStackQueue::StackBox::hover( bool on )
  3882. {
  3883. }