CBattleInterface.cpp 150 KB

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