CBattleInterface.cpp 144 KB

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