CBattleInterface.cpp 130 KB

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