CBattleInterface.cpp 126 KB

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