CBattleInterface.cpp 128 KB

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