CBattleInterface.cpp 126 KB

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