CBattleInterface.cpp 149 KB

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