CBattleInterface.cpp 144 KB

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