CGameState.cpp 144 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077
  1. #define VCMI_DLL
  2. #include "CCampaignHandler.h"
  3. #include <algorithm>
  4. #include <queue>
  5. #include <fstream>
  6. #include "CGameState.h"
  7. #include <boost/random/linear_congruential.hpp>
  8. #include "CDefObjInfoHandler.h"
  9. #include "CArtHandler.h"
  10. #include "CBuildingHandler.h"
  11. #include "CGeneralTextHandler.h"
  12. #include "CTownHandler.h"
  13. #include "CSpellHandler.h"
  14. #include "CHeroHandler.h"
  15. #include "CObjectHandler.h"
  16. #include "CCreatureHandler.h"
  17. //#include "../lib/IGameCallback.h"
  18. #include "VCMI_Lib.h"
  19. #include "Connection.h"
  20. #include "map.h"
  21. #include "../StartInfo.h"
  22. #include "NetPacks.h"
  23. #include <boost/foreach.hpp>
  24. #include <boost/lexical_cast.hpp>
  25. #include <boost/thread.hpp>
  26. #include <boost/thread/shared_mutex.hpp>
  27. #include <boost/assign/list_of.hpp>
  28. #include "RegisterTypes.cpp"
  29. #include <algorithm>
  30. #include <numeric>
  31. #include "CMapInfo.h"
  32. boost::rand48 ran;
  33. class CGObjectInstance;
  34. #ifdef min
  35. #undef min
  36. #endif
  37. #ifdef max
  38. #undef max
  39. #endif
  40. /*
  41. * CGameState.cpp, part of VCMI engine
  42. *
  43. * Authors: listed in file AUTHORS in main folder
  44. *
  45. * License: GNU General Public License v2.0 or later
  46. * Full text of license available in license.txt file, in main folder
  47. *
  48. */
  49. void foofoofoo()
  50. {
  51. //never called function to force instantation of templates
  52. int *ccc = NULL;
  53. registerTypes((CISer<CConnection>&)*ccc);
  54. registerTypes((COSer<CConnection>&)*ccc);
  55. registerTypes((CSaveFile&)*ccc);
  56. registerTypes((CLoadFile&)*ccc);
  57. registerTypes((CTypeList&)*ccc);
  58. }
  59. template <typename T> class CApplyOnGS;
  60. class CBaseForGSApply
  61. {
  62. public:
  63. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  64. virtual ~CBaseForGSApply(){};
  65. template<typename U> static CBaseForGSApply *getApplier(const U * t=NULL)
  66. {
  67. return new CApplyOnGS<U>;
  68. }
  69. };
  70. template <typename T> class CApplyOnGS : public CBaseForGSApply
  71. {
  72. public:
  73. void applyOnGS(CGameState *gs, void *pack) const
  74. {
  75. T *ptr = static_cast<T*>(pack);
  76. while(!gs->mx->try_lock())
  77. boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  78. ptr->applyGs(gs);
  79. gs->mx->unlock();
  80. }
  81. };
  82. static CApplier<CBaseForGSApply> *applierGs = NULL;
  83. class IObjectCaller
  84. {
  85. public:
  86. virtual void preInit()=0;
  87. virtual void postInit()=0;
  88. };
  89. template <typename T>
  90. class CObjectCaller : public IObjectCaller
  91. {
  92. public:
  93. void preInit()
  94. {
  95. //T::preInit();
  96. }
  97. void postInit()
  98. {
  99. //T::postInit();
  100. }
  101. };
  102. class CObjectCallersHandler
  103. {
  104. public:
  105. std::vector<IObjectCaller*> apps;
  106. template<typename T> void registerType(const T * t=NULL)
  107. {
  108. apps.push_back(new CObjectCaller<T>);
  109. }
  110. CObjectCallersHandler()
  111. {
  112. registerTypes1(*this);
  113. }
  114. ~CObjectCallersHandler()
  115. {
  116. for (size_t i = 0; i < apps.size(); i++)
  117. delete apps[i];
  118. }
  119. void preInit()
  120. {
  121. // for (size_t i = 0; i < apps.size(); i++)
  122. // apps[i]->preInit();
  123. }
  124. void postInit()
  125. {
  126. //for (size_t i = 0; i < apps.size(); i++)
  127. //apps[i]->postInit();
  128. }
  129. } *objCaller = NULL;
  130. void MetaString::getLocalString(const std::pair<ui8,ui32> &txt, std::string &dst) const
  131. {
  132. int type = txt.first, ser = txt.second;
  133. if(type == ART_NAMES)
  134. {
  135. dst = VLC->arth->artifacts[ser]->Name();
  136. }
  137. else if(type == CRE_PL_NAMES)
  138. {
  139. dst = VLC->creh->creatures[ser]->namePl;
  140. }
  141. else if(type == MINE_NAMES)
  142. {
  143. dst = VLC->generaltexth->mines[ser].first;
  144. }
  145. else if(type == MINE_EVNTS)
  146. {
  147. dst = VLC->generaltexth->mines[ser].second;
  148. }
  149. else if(type == SPELL_NAME)
  150. {
  151. dst = VLC->spellh->spells[ser]->name;
  152. }
  153. else if(type == CRE_SING_NAMES)
  154. {
  155. dst = VLC->creh->creatures[ser]->nameSing;
  156. }
  157. else if(type == ART_DESCR)
  158. {
  159. dst = VLC->arth->artifacts[ser]->Description();
  160. }
  161. else
  162. {
  163. std::vector<std::string> *vec;
  164. switch(type)
  165. {
  166. case GENERAL_TXT:
  167. vec = &VLC->generaltexth->allTexts;
  168. break;
  169. case XTRAINFO_TXT:
  170. vec = &VLC->generaltexth->xtrainfo;
  171. break;
  172. case OBJ_NAMES:
  173. vec = &VLC->generaltexth->names;
  174. break;
  175. case RES_NAMES:
  176. vec = &VLC->generaltexth->restypes;
  177. break;
  178. case ARRAY_TXT:
  179. vec = &VLC->generaltexth->arraytxt;
  180. break;
  181. case CREGENS:
  182. vec = &VLC->generaltexth->creGens;
  183. break;
  184. case CREGENS4:
  185. vec = &VLC->generaltexth->creGens4;
  186. break;
  187. case ADVOB_TXT:
  188. vec = &VLC->generaltexth->advobtxt;
  189. break;
  190. case ART_EVNTS:
  191. vec = &VLC->generaltexth->artifEvents;
  192. break;
  193. case SEC_SKILL_NAME:
  194. vec = &VLC->generaltexth->skillName;
  195. break;
  196. case COLOR:
  197. vec = &VLC->generaltexth->capColors;
  198. break;
  199. }
  200. dst = (*vec)[ser];
  201. }
  202. }
  203. DLL_EXPORT void MetaString::toString(std::string &dst) const
  204. {
  205. size_t exSt = 0, loSt = 0, nums = 0;
  206. dst.clear();
  207. for(size_t i=0;i<message.size();++i)
  208. {//TEXACT_STRING, TLOCAL_STRING, TNUMBER, TREPLACE_ESTRING, TREPLACE_LSTRING, TREPLACE_NUMBER
  209. switch(message[i])
  210. {
  211. case TEXACT_STRING:
  212. dst += exactStrings[exSt++];
  213. break;
  214. case TLOCAL_STRING:
  215. {
  216. std::string hlp;
  217. getLocalString(localStrings[loSt++], hlp);
  218. dst += hlp;
  219. }
  220. break;
  221. case TNUMBER:
  222. dst += boost::lexical_cast<std::string>(numbers[nums++]);
  223. break;
  224. case TREPLACE_ESTRING:
  225. dst.replace (dst.find("%s"), 2, exactStrings[exSt++]);
  226. break;
  227. case TREPLACE_LSTRING:
  228. {
  229. std::string hlp;
  230. getLocalString(localStrings[loSt++], hlp);
  231. dst.replace (dst.find("%s"), 2, hlp);
  232. }
  233. break;
  234. case TREPLACE_NUMBER:
  235. dst.replace (dst.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  236. break;
  237. case TREPLACE_PLUSNUMBER:
  238. dst.replace (dst.find("%+d"), 3, '+' + boost::lexical_cast<std::string>(numbers[nums++]));
  239. break;
  240. default:
  241. tlog1 << "MetaString processing error!\n";
  242. break;
  243. }
  244. }
  245. }
  246. DLL_EXPORT std::string MetaString::toString() const
  247. {
  248. std::string ret;
  249. toString(ret);
  250. return ret;
  251. }
  252. DLL_EXPORT std::string MetaString::buildList () const
  253. ///used to handle loot from creature bank
  254. {
  255. size_t exSt = 0, loSt = 0, nums = 0;
  256. std::string lista;
  257. for (int i = 0; i < message.size(); ++i)
  258. {
  259. if (i > 0 && message[i] == TEXACT_STRING || message[i] == TLOCAL_STRING)
  260. {
  261. if (exSt == exactStrings.size() - 1)
  262. lista += VLC->generaltexth->allTexts[141]; //" and "
  263. else
  264. lista += ", ";
  265. }
  266. switch (message[i])
  267. {
  268. case TEXACT_STRING:
  269. lista += exactStrings[exSt++];
  270. break;
  271. case TLOCAL_STRING:
  272. {
  273. std::string hlp;
  274. getLocalString (localStrings[loSt++], hlp);
  275. lista += hlp;
  276. }
  277. break;
  278. case TNUMBER:
  279. lista += boost::lexical_cast<std::string>(numbers[nums++]);
  280. break;
  281. case TREPLACE_ESTRING:
  282. lista.replace (lista.find("%s"), 2, exactStrings[exSt++]);
  283. break;
  284. case TREPLACE_LSTRING:
  285. {
  286. std::string hlp;
  287. getLocalString (localStrings[loSt++], hlp);
  288. lista.replace (lista.find("%s"), 2, hlp);
  289. }
  290. break;
  291. case TREPLACE_NUMBER:
  292. lista.replace (lista.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  293. break;
  294. default:
  295. tlog1 << "MetaString processing error!\n";
  296. }
  297. }
  298. return lista;
  299. }
  300. void MetaString::addCreReplacement(TCreature id, TQuantity count) //adds sing or plural name;
  301. {
  302. assert(count);
  303. if (count == 1)
  304. addReplacement (CRE_SING_NAMES, id);
  305. else
  306. addReplacement (CRE_PL_NAMES, id);
  307. }
  308. void MetaString::addReplacement(const CStackBasicDescriptor &stack)
  309. {
  310. assert(stack.count); //valid count
  311. assert(stack.type); //valid type
  312. addReplacement(stack.type->idNumber, stack.count);
  313. }
  314. static CGObjectInstance * createObject(int id, int subid, int3 pos, int owner)
  315. {
  316. CGObjectInstance * nobj;
  317. switch(id)
  318. {
  319. case HEROI_TYPE: //hero
  320. {
  321. CGHeroInstance * nobj = new CGHeroInstance();
  322. nobj->pos = pos;
  323. nobj->tempOwner = owner;
  324. nobj->subID = subid;
  325. //nobj->initHero(ran);
  326. return nobj;
  327. }
  328. case TOWNI_TYPE: //town
  329. nobj = new CGTownInstance;
  330. break;
  331. default: //rest of objects
  332. nobj = new CGObjectInstance;
  333. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  334. break;
  335. }
  336. nobj->ID = id;
  337. nobj->subID = subid;
  338. if(!nobj->defInfo)
  339. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  340. nobj->pos = pos;
  341. //nobj->state = NULL;//new CLuaObjectScript();
  342. nobj->tempOwner = owner;
  343. nobj->defInfo->id = id;
  344. nobj->defInfo->subid = subid;
  345. //assigning defhandler
  346. if(nobj->ID==HEROI_TYPE || nobj->ID==TOWNI_TYPE)
  347. return nobj;
  348. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  349. return nobj;
  350. }
  351. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  352. {
  353. for(unsigned int g=0; g<stacks.size(); ++g)
  354. {
  355. if(stacks[g]->ID == stackID && (!onlyAlive || stacks[g]->alive()))
  356. return stacks[g];
  357. }
  358. return NULL;
  359. }
  360. const CStack * BattleInfo::getStack(int stackID, bool onlyAlive) const
  361. {
  362. return const_cast<BattleInfo * const>(this)->getStack(stackID, onlyAlive);
  363. }
  364. CStack * BattleInfo::getStackT(THex tileID, bool onlyAlive)
  365. {
  366. for(unsigned int g=0; g<stacks.size(); ++g)
  367. {
  368. if(stacks[g]->position == tileID
  369. || (stacks[g]->doubleWide() && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  370. || (stacks[g]->doubleWide() && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  371. {
  372. if(!onlyAlive || stacks[g]->alive())
  373. {
  374. return stacks[g];
  375. }
  376. }
  377. }
  378. return NULL;
  379. }
  380. const CStack * BattleInfo::getStackT(THex tileID, bool onlyAlive) const
  381. {
  382. return const_cast<BattleInfo * const>(this)->getStackT(tileID, onlyAlive);
  383. }
  384. void BattleInfo::getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<int> & occupyable, bool flying, int stackToOmmit) const
  385. {
  386. memset(accessibility, 1, BFIELD_SIZE); //initialize array with trues
  387. //removing accessibility for side columns of hexes
  388. for(int v = 0; v < BFIELD_SIZE; ++v)
  389. {
  390. if( v % BFIELD_WIDTH == 0 || v % BFIELD_WIDTH == (BFIELD_WIDTH - 1) )
  391. accessibility[v] = false;
  392. }
  393. for(unsigned int g=0; g<stacks.size(); ++g)
  394. {
  395. if(!stacks[g]->alive() || stacks[g]->ID==stackToOmmit || stacks[g]->position < 0) //we don't want to lock position of this stack (eg. if it's a turret)
  396. continue;
  397. accessibility[stacks[g]->position] = false;
  398. if(stacks[g]->doubleWide()) //if it's a double hex creature
  399. {
  400. if(stacks[g]->attackerOwned)
  401. accessibility[stacks[g]->position-1] = false;
  402. else
  403. accessibility[stacks[g]->position+1] = false;
  404. }
  405. }
  406. //obstacles
  407. for(unsigned int b=0; b<obstacles.size(); ++b)
  408. {
  409. std::vector<int> blocked = VLC->heroh->obstacles[obstacles[b].ID].getBlocked(obstacles[b].pos);
  410. for(unsigned int c=0; c<blocked.size(); ++c)
  411. {
  412. if(blocked[c] >=0 && blocked[c] < BFIELD_SIZE)
  413. accessibility[blocked[c]] = false;
  414. }
  415. }
  416. //walls
  417. if(siege > 0)
  418. {
  419. static const int permanentlyLocked[] = {12, 45, 78, 112, 147, 165};
  420. for(int b=0; b<ARRAY_COUNT(permanentlyLocked); ++b)
  421. {
  422. accessibility[permanentlyLocked[b]] = false;
  423. }
  424. static const std::pair<int, int> lockedIfNotDestroyed[] = //(which part of wall, which hex is blocked if this part of wall is not destroyed
  425. {std::make_pair(2, 182), std::make_pair(3, 130), std::make_pair(4, 62), std::make_pair(5, 29)};
  426. for(int b=0; b<ARRAY_COUNT(lockedIfNotDestroyed); ++b)
  427. {
  428. if(si.wallState[lockedIfNotDestroyed[b].first] < 3)
  429. {
  430. accessibility[lockedIfNotDestroyed[b].second] = false;
  431. }
  432. }
  433. //gate
  434. if(attackerOwned && si.wallState[7] < 3) //if it attacker's unit and gate is not destroyed
  435. {
  436. accessibility[95] = accessibility[96] = false; //block gate's hexes
  437. }
  438. }
  439. //occupyability
  440. if(addOccupiable && twoHex)
  441. {
  442. std::set<int> rem; //tiles to unlock
  443. for(int h=0; h<BFIELD_HEIGHT; ++h)
  444. {
  445. for(int w=1; w<BFIELD_WIDTH-1; ++w)
  446. {
  447. int hex = h * BFIELD_WIDTH + w;
  448. if(!isAccessible(hex, accessibility, twoHex, attackerOwned, flying, true)
  449. && (attackerOwned ? isAccessible(hex+1, accessibility, twoHex, attackerOwned, flying, true) : isAccessible(hex-1, accessibility, twoHex, attackerOwned, flying, true) )
  450. )
  451. rem.insert(hex);
  452. }
  453. }
  454. occupyable = rem;
  455. /*for(std::set<int>::const_iterator it = rem.begin(); it != rem.end(); ++it)
  456. {
  457. accessibility[*it] = true;
  458. }*/
  459. }
  460. }
  461. bool BattleInfo::isAccessible(int hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos)
  462. {
  463. if(flying && !lastPos)
  464. return true;
  465. if(twoHex)
  466. {
  467. //if given hex is accessible and appropriate adjacent one is free too
  468. return accessibility[hex] && accessibility[hex + (attackerOwned ? -1 : 1 )];
  469. }
  470. else
  471. {
  472. return accessibility[hex];
  473. }
  474. }
  475. void BattleInfo::makeBFS(int start, bool *accessibility, int *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying, bool fillPredecessors) const //both pointers must point to the at least 187-elements int arrays
  476. {
  477. //inits
  478. for(int b=0; b<BFIELD_SIZE; ++b)
  479. predecessor[b] = -1;
  480. for(int g=0; g<BFIELD_SIZE; ++g)
  481. dists[g] = 100000000;
  482. std::queue< std::pair<int, bool> > hexq; //bfs queue <hex, accessible> (second filed used only if fillPredecessors is true)
  483. hexq.push(std::make_pair(start, true));
  484. dists[hexq.front().first] = 0;
  485. int curNext = -1; //for bfs loop only (helper var)
  486. while(!hexq.empty()) //bfs loop
  487. {
  488. std::pair<int, bool> curHex = hexq.front();
  489. std::vector<int> neighbours = neighbouringTiles(curHex.first);
  490. hexq.pop();
  491. for(unsigned int nr=0; nr<neighbours.size(); nr++)
  492. {
  493. curNext = neighbours[nr]; //if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  494. bool accessible = isAccessible(curNext, accessibility, twoHex, attackerOwned, flying, dists[curHex.first]+1 == dists[curNext]);
  495. if( dists[curHex.first]+1 >= dists[curNext] )
  496. continue;
  497. if(accessible && curHex.second)
  498. {
  499. hexq.push(std::make_pair(curNext, true));
  500. dists[curNext] = dists[curHex.first] + 1;
  501. }
  502. else if(fillPredecessors && !(accessible && !curHex.second))
  503. {
  504. hexq.push(std::make_pair(curNext, false));
  505. dists[curNext] = dists[curHex.first] + 1;
  506. }
  507. predecessor[curNext] = curHex.first;
  508. }
  509. }
  510. };
  511. std::vector<int> BattleInfo::getAccessibility(int stackID, bool addOccupiable) const
  512. {
  513. std::vector<int> ret;
  514. bool ac[BFIELD_SIZE];
  515. const CStack *s = getStack(stackID, false); //this function is called from healedOrResurrected, so our stack can be dead
  516. if(s->position < 0) //turrets
  517. return std::vector<int>();
  518. std::set<int> occupyable;
  519. getAccessibilityMap(ac, s->doubleWide(), s->attackerOwned, addOccupiable, occupyable, s->hasBonusOfType(Bonus::FLYING), stackID);
  520. int pr[BFIELD_SIZE], dist[BFIELD_SIZE];
  521. makeBFS(s->position, ac, pr, dist, s->doubleWide(), s->attackerOwned, s->hasBonusOfType(Bonus::FLYING), false);
  522. if(s->doubleWide())
  523. {
  524. if(!addOccupiable)
  525. {
  526. std::vector<int> rem;
  527. for(int b=0; b<BFIELD_SIZE; ++b)
  528. {
  529. //don't take into account most left and most right columns of hexes
  530. if( b % BFIELD_WIDTH == 0 || b % BFIELD_WIDTH == BFIELD_WIDTH - 1 )
  531. continue;
  532. if( ac[b] && !(s->attackerOwned ? ac[b-1] : ac[b+1]) )
  533. {
  534. rem.push_back(b);
  535. }
  536. }
  537. for(unsigned int g=0; g<rem.size(); ++g)
  538. {
  539. ac[rem[g]] = false;
  540. }
  541. //removing accessibility for side hexes
  542. for(int v=0; v<BFIELD_SIZE; ++v)
  543. if(s->attackerOwned ? (v%BFIELD_WIDTH)==1 : (v%BFIELD_WIDTH)==(BFIELD_WIDTH - 2))
  544. ac[v] = false;
  545. }
  546. }
  547. for (int i=0; i < BFIELD_SIZE ; ++i) {
  548. if(
  549. ( ( !addOccupiable && dist[i] <= s->Speed() && ac[i] ) || ( addOccupiable && dist[i] <= s->Speed() && isAccessible(i, ac, s->doubleWide(), s->attackerOwned, s->hasBonusOfType(Bonus::FLYING), true) ) )//we can reach it
  550. || (vstd::contains(occupyable, i) && ( dist[ i + (s->attackerOwned ? 1 : -1 ) ] <= s->Speed() ) &&
  551. ac[i + (s->attackerOwned ? 1 : -1 )] ) //it's occupyable and we can reach adjacent hex
  552. )
  553. {
  554. ret.push_back(i);
  555. }
  556. }
  557. return ret;
  558. }
  559. bool BattleInfo::isStackBlocked(int ID)
  560. {
  561. CStack *our = getStack(ID);
  562. if(our->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  563. return false;
  564. for(unsigned int i=0; i<stacks.size();i++)
  565. {
  566. if( !stacks[i]->alive()
  567. || stacks[i]->owner==our->owner
  568. )
  569. continue; //we omit dead and allied stacks
  570. if(stacks[i]->doubleWide())
  571. {
  572. if( mutualPosition(stacks[i]->position, our->position) >= 0
  573. || mutualPosition(stacks[i]->position + (stacks[i]->attackerOwned ? -1 : 1), our->position) >= 0)
  574. return true;
  575. }
  576. else
  577. {
  578. if( mutualPosition(stacks[i]->position, our->position) >= 0 )
  579. return true;
  580. }
  581. }
  582. return false;
  583. }
  584. signed char BattleInfo::mutualPosition(THex hex1, THex hex2)
  585. {
  586. if(hex2 == hex1 - ( (hex1/17)%2 ? 18 : 17 )) //top left
  587. return 0;
  588. if(hex2 == hex1 - ( (hex1/17)%2 ? 17 : 16 )) //top right
  589. return 1;
  590. if(hex2 == hex1 - 1 && hex1%17 != 0) //left
  591. return 5;
  592. if(hex2 == hex1 + 1 && hex1%17 != 16) //right
  593. return 2;
  594. if(hex2 == hex1 + ( (hex1/17)%2 ? 16 : 17 )) //bottom left
  595. return 4;
  596. if(hex2 == hex1 + ( (hex1/17)%2 ? 17 : 18 )) //bottom right
  597. return 3;
  598. return -1;
  599. }
  600. std::vector<int> BattleInfo::neighbouringTiles(int hex)
  601. {
  602. #define CHECK_AND_PUSH(tile) {int hlp = (tile); if(hlp>=0 && hlp<BFIELD_SIZE && (hlp%BFIELD_WIDTH!=16) && hlp%BFIELD_WIDTH) ret.push_back(hlp);}
  603. std::vector<int> ret;
  604. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 18 : 17 ));
  605. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 17 : 16 ));
  606. CHECK_AND_PUSH(hex - 1);
  607. CHECK_AND_PUSH(hex + 1);
  608. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 16 : 17 ));
  609. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 17 : 18 ));
  610. #undef CHECK_AND_PUSH
  611. return ret;
  612. }
  613. std::pair< std::vector<int>, int > BattleInfo::getPath(int start, int dest, bool*accessibility, bool flyingCreature, bool twoHex, bool attackerOwned)
  614. {
  615. int predecessor[BFIELD_SIZE]; //for getting the Path
  616. int dist[BFIELD_SIZE]; //calculated distances
  617. makeBFS(start, accessibility, predecessor, dist, twoHex, attackerOwned, flyingCreature, false);
  618. if(predecessor[dest] == -1) //cannot reach destination
  619. {
  620. return std::make_pair(std::vector<int>(), 0);
  621. }
  622. //making the Path
  623. std::vector<int> path;
  624. int curElem = dest;
  625. while(curElem != start)
  626. {
  627. path.push_back(curElem);
  628. curElem = predecessor[curElem];
  629. }
  630. return std::make_pair(path, dist[dest]);
  631. }
  632. CStack::CStack(const CStackInstance *Base, int O, int I, bool AO, int S)
  633. : base(Base), ID(I), owner(O), slot(S), attackerOwned(AO), position(-1),
  634. counterAttacks(1)
  635. {
  636. assert(base);
  637. type = base->type;
  638. count = baseAmount = base->count;
  639. }
  640. CStack::CStack()
  641. {
  642. init();
  643. }
  644. CStack::CStack(const CStackBasicDescriptor *stack, int O, int I, bool AO, int S)
  645. : base(NULL), ID(I), owner(O), slot(S), attackerOwned(AO), position(-1), counterAttacks(1)
  646. {
  647. type = stack->type;
  648. count = baseAmount = stack->count;
  649. }
  650. void CStack::init()
  651. {
  652. base = NULL;
  653. type = NULL;
  654. ID = -1;
  655. count = baseAmount = -1;
  656. firstHPleft = -1;
  657. owner = 255;
  658. slot = 255;
  659. attackerOwned = false;
  660. position = -1;
  661. counterAttacks = -1;
  662. }
  663. void CStack::postInit()
  664. {
  665. assert(type);
  666. assert(parents.size());
  667. firstHPleft = valOfBonuses(Bonus::STACK_HEALTH);
  668. shots = getCreature()->shots;
  669. counterAttacks = 1 + valOfBonuses(Bonus::ADDITIONAL_RETALIATION);
  670. state.insert(ALIVE); //alive state indication
  671. assert(firstHPleft > 0);
  672. }
  673. ui32 CStack::Speed( int turn /*= 0*/ ) const
  674. {
  675. if(hasBonus(Selector::type(Bonus::SIEGE_WEAPON) && Selector::turns(turn))) //war machines cannot move
  676. return 0;
  677. int speed = valOfBonuses(Selector::type(Bonus::STACKS_SPEED) && Selector::turns(turn));
  678. int percentBonus = 0;
  679. BOOST_FOREACH(const Bonus *b, bonuses)
  680. {
  681. if(b->type == Bonus::STACKS_SPEED)
  682. {
  683. percentBonus += b->additionalInfo;
  684. }
  685. }
  686. speed = ((100 + percentBonus) * speed)/100;
  687. //bind effect check
  688. if(getEffect(72))
  689. {
  690. return 0;
  691. }
  692. return speed;
  693. }
  694. const Bonus * CStack::getEffect( ui16 id, int turn /*= 0*/ ) const
  695. {
  696. BOOST_FOREACH(Bonus *it, bonuses)
  697. {
  698. if(it->source == Bonus::SPELL_EFFECT && it->id == id)
  699. {
  700. if(!turn || it->turnsRemain > turn)
  701. return &(*it);
  702. }
  703. }
  704. return NULL;
  705. }
  706. void CStack::stackEffectToFeature(BonusList & sf, const Bonus & sse)
  707. {
  708. // si32 power = VLC->spellh->spells[sse.id]->powers[sse.val];
  709. // Bonus * bonus = getBonus(Selector::typeSybtype(Bonus::SPECIAL_PECULIAR_ENCHANT, sse.id));
  710. // if (bonus)
  711. // {
  712. // switch(bonus->additionalInfo)
  713. // {
  714. // case 0: //normal
  715. // switch(type->level)
  716. // {
  717. // case 1: case 2:
  718. // power += 3; //it doesn't necessarily make sense for some spells, use it wisely
  719. // break;
  720. // case 3: case 4:
  721. // power += 2;
  722. // break;
  723. // case 5: case 6:
  724. // power += 1;
  725. // break;
  726. // }
  727. // break;
  728. // case 1: //only Coronius as yet
  729. // power = std::max(5 - type->level, 0);
  730. // break;
  731. // }
  732. // }
  733. //
  734. // switch(sse.id)
  735. // {
  736. // case 27: //shield
  737. // sf.push_back(featureGenerator(Bonus::GENERAL_DAMAGE_REDUCTION, 0, power, sse.turnsRemain));
  738. // sf.back().id = sse.id;
  739. // break;
  740. // case 28: //air shield
  741. // sf.push_back(featureGenerator(Bonus::GENERAL_DAMAGE_REDUCTION, 1, power, sse.turnsRemain));
  742. // sf.back().id = sse.id;
  743. // break;
  744. // case 29: //fire shield
  745. // sf.push_back(featureGenerator(Bonus::FIRE_SHIELD, 0, power, sse.turnsRemain));
  746. // sf.back().id = sse.id;
  747. // break;
  748. // case 30: //protection from air
  749. // sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 0, power, sse.turnsRemain));
  750. // sf.back().id = sse.id;
  751. // break;
  752. // case 31: //protection from fire
  753. // sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 1, power, sse.turnsRemain));
  754. // sf.back().id = sse.id;
  755. // break;
  756. // case 32: //protection from water
  757. // sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 2, power, sse.turnsRemain));
  758. // sf.back().id = sse.id;
  759. // break;
  760. // case 33: //protection from earth
  761. // sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 3, power, sse.turnsRemain));
  762. // sf.back().id = sse.id;
  763. // break;
  764. // case 34: //anti-magic
  765. // sf.push_back(featureGenerator(Bonus::LEVEL_SPELL_IMMUNITY, 0, power - 1, sse.turnsRemain));
  766. // sf.back().id = sse.id;
  767. // break;
  768. // case 41: //bless
  769. // if (hasBonusOfType(Bonus::SPECIAL_BLESS_DAMAGE, 41)) //TODO: better handling of bonus percentages
  770. // {
  771. // int damagePercent = dynamic_cast<const CGHeroInstance*>(armyObj)->level * valOfBonuses(Bonus::SPECIAL_BLESS_DAMAGE, 41) / type->level;
  772. // sf.push_back(featureGenerator(Bonus::CREATURE_DAMAGE, 0, damagePercent, sse.turnsRemain));
  773. // sf.back().id = sse.id;
  774. // sf.back().valType = Bonus::PERCENT_TO_ALL;
  775. // }
  776. // sf.push_back(featureGenerator(Bonus::ALWAYS_MAXIMUM_DAMAGE, -1, power, sse.turnsRemain));
  777. // sf.back().id = sse.id;
  778. // break;
  779. // case 42: //curse
  780. // sf.push_back(featureGenerator(Bonus::ALWAYS_MINIMUM_DAMAGE, -1, -1 * power, sse.turnsRemain, sse.val >= 2 ? 20 : 0));
  781. // sf.back().id = sse.id;
  782. // break;
  783. // case 43: //bloodlust
  784. // sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain, 0, Bonus::ONLY_MELEE_FIGHT));
  785. // sf.back().id = sse.id;
  786. // break;
  787. // case 44: //precision
  788. // sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain, 0, Bonus::ONLY_DISTANCE_FIGHT));
  789. // sf.back().id = sse.id;
  790. // break;
  791. // case 45: //weakness
  792. // sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, -1 * power, sse.turnsRemain));
  793. // sf.back().id = sse.id;
  794. // break;
  795. // case 46: //stone skin
  796. // sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power, sse.turnsRemain));
  797. // sf.back().id = sse.id;
  798. // break;
  799. // case 47: //disrupting ray
  800. // sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -1 * power, sse.turnsRemain));
  801. // sf.back().id = sse.id;
  802. // break;
  803. // case 48: //prayer
  804. // sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain));
  805. // sf.back().id = sse.id;
  806. // sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power, sse.turnsRemain));
  807. // sf.back().id = sse.id;
  808. // sf.push_back(featureGenerator(Bonus::STACKS_SPEED, 0, power, sse.turnsRemain));
  809. // sf.back().id = sse.id;
  810. // break;
  811. // case 49: //mirth
  812. // sf.push_back(featureGenerator(Bonus::MORALE, 0, power, sse.turnsRemain));
  813. // sf.back().id = sse.id;
  814. // break;
  815. // case 50: //sorrow
  816. // sf.push_back(featureGenerator(Bonus::MORALE, 0, -1 * power, sse.turnsRemain));
  817. // sf.back().id = sse.id;
  818. // break;
  819. // case 51: //fortune
  820. // sf.push_back(featureGenerator(Bonus::LUCK, 0, power, sse.turnsRemain));
  821. // sf.back().id = sse.id;
  822. // break;
  823. // case 52: //misfortune
  824. // sf.push_back(featureGenerator(Bonus::LUCK, 0, -1 * power, sse.turnsRemain));
  825. // sf.back().id = sse.id;
  826. // break;
  827. // case 53: //haste
  828. // sf.push_back(featureGenerator(Bonus::STACKS_SPEED, 0, power, sse.turnsRemain));
  829. // sf.back().id = sse.id;
  830. // break;
  831. // case 54: //slow
  832. // sf.push_back(featureGeneratorVT(Bonus::STACKS_SPEED, 0, -1 * ( 100 - power ), sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  833. // sf.back().id = sse.id;
  834. // break;
  835. // case 55: //slayer
  836. // if (bonus) //Coronius
  837. // {
  838. // sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain));
  839. // sf.back().id = sse.id;
  840. // }
  841. // sf.push_back(featureGenerator(Bonus::SLAYER, 0, sse.val, sse.turnsRemain));
  842. // sf.back().id = sse.id;
  843. // break;
  844. // case 56: //frenzy
  845. // sf.push_back(featureGenerator(Bonus::IN_FRENZY, 0, VLC->spellh->spells[56]->powers[sse.val]/100.0, sse.turnsRemain));
  846. // sf.back().id = sse.id;
  847. // break;
  848. // case 58: //counterstrike
  849. // sf.push_back(featureGenerator(Bonus::ADDITIONAL_RETALIATION, 0, power, sse.turnsRemain));
  850. // sf.back().id = sse.id;
  851. // break;
  852. // case 59: //bersek
  853. // sf.push_back(featureGenerator(Bonus::ATTACKS_NEAREST_CREATURE, 0, sse.val, sse.turnsRemain));
  854. // sf.back().id = sse.id;
  855. // break;
  856. // case 60: //hypnotize
  857. // sf.push_back(featureGenerator(Bonus::HYPNOTIZED, 0, sse.val, sse.turnsRemain));
  858. // sf.back().id = sse.id;
  859. // break;
  860. // case 61: //forgetfulness
  861. // sf.push_back(featureGenerator(Bonus::FORGETFULL, 0, sse.val, sse.turnsRemain));
  862. // sf.back().id = sse.id;
  863. // break;
  864. // case 62: //blind
  865. // sf.push_back(makeFeature(Bonus::NOT_ACTIVE, Bonus::UNITL_BEING_ATTACKED | Bonus::N_TURNS, 0, 0, Bonus::SPELL_EFFECT, sse.turnsRemain));
  866. // sf.back().id = sse.id;
  867. // sf.push_back(makeFeature(Bonus::GENERAL_ATTACK_REDUCTION, Bonus::UNTIL_ATTACK | Bonus::N_TURNS, 0, power, Bonus::SPELL_EFFECT, sse.turnsRemain));
  868. // sf.back().id = sse.id;
  869. // break;
  870. // }
  871. }
  872. ui8 CStack::howManyEffectsSet(ui16 id) const
  873. {
  874. ui8 ret = 0;
  875. BOOST_FOREACH(const Bonus *it, bonuses)
  876. if(it->source == Bonus::SPELL_EFFECT && it->id == id) //effect found
  877. {
  878. ++ret;
  879. }
  880. return ret;
  881. }
  882. bool CStack::willMove(int turn /*= 0*/) const
  883. {
  884. return ( turn ? true : !vstd::contains(state, DEFENDING) )
  885. && !moved(turn)
  886. && canMove(turn);
  887. }
  888. bool CStack::canMove( int turn /*= 0*/ ) const
  889. {
  890. return alive()
  891. && !hasBonus(Selector::type(Bonus::NOT_ACTIVE) && Selector::turns(turn)); //eg. Ammo Cart or blinded creature
  892. }
  893. bool CStack::moved( int turn /*= 0*/ ) const
  894. {
  895. if(!turn)
  896. return vstd::contains(state, MOVED);
  897. else
  898. return false;
  899. }
  900. bool CStack::doubleWide() const
  901. {
  902. return getCreature()->doubleWide;
  903. }
  904. int CStack::occupiedHex() const
  905. {
  906. if (doubleWide())
  907. {
  908. if (attackerOwned)
  909. return position - 1;
  910. else
  911. return position + 1;
  912. }
  913. else
  914. {
  915. return -1;
  916. }
  917. }
  918. BonusList CStack::getSpellBonuses() const
  919. {
  920. return getBonuses(Selector::sourceTypeSel(Bonus::CASTED_SPELL));
  921. }
  922. std::vector<si32> CStack::activeSpells() const
  923. {
  924. std::vector<si32> ret;
  925. BonusList spellEffects = getSpellBonuses();
  926. BOOST_FOREACH(const Bonus *it, spellEffects)
  927. {
  928. if (!vstd::contains(ret, it->id)) //do not duplicate spells with multiple effects
  929. ret.push_back(it->id);
  930. }
  931. return ret;
  932. }
  933. CStack::~CStack()
  934. {
  935. detachFromAll();
  936. if(vstd::contains(state, SUMMONED))
  937. delNull(base);
  938. }
  939. const CGHeroInstance * CStack::getMyHero() const
  940. {
  941. if(base)
  942. return dynamic_cast<const CGHeroInstance *>(base->armyObj);
  943. else //we are attached directly?
  944. BOOST_FOREACH(const CBonusSystemNode *n, parents)
  945. if(n->nodeType == HERO)
  946. dynamic_cast<const CGHeroInstance *>(n);
  947. return NULL;
  948. }
  949. std::string CStack::nodeName() const
  950. {
  951. std::ostringstream oss;
  952. oss << "Battle stack [" << ID << "]: " << count << " creatures of ";
  953. if(type)
  954. oss << type->namePl;
  955. else
  956. oss << "[UNDEFINED TYPE]";
  957. oss << " from slot " << (int)slot;
  958. if(base && base->armyObj)
  959. oss << " of armyobj=" << base->armyObj->id;
  960. return oss.str();
  961. }
  962. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native, int player, const CTown *town, bmap<ui32, ConstTransitivePtr<CGHeroInstance> > &available, const CHeroClass *bannedClass /*= NULL*/) const
  963. {
  964. CGHeroInstance *ret = NULL;
  965. if(player<0 || player>=PLAYER_LIMIT)
  966. {
  967. tlog1 << "Cannot pick hero for " << town->Name() << ". Wrong owner!\n";
  968. return NULL;
  969. }
  970. std::vector<CGHeroInstance *> pool;
  971. if(native)
  972. {
  973. for(bmap<ui32, ConstTransitivePtr<CGHeroInstance> >::iterator i=available.begin(); i!=available.end(); i++)
  974. {
  975. if(pavailable.find(i->first)->second & 1<<player
  976. && i->second->type->heroType/2 == town->typeID)
  977. {
  978. pool.push_back(i->second); //get all avaliable heroes
  979. }
  980. }
  981. if(!pool.size())
  982. {
  983. tlog1 << "Cannot pick native hero for " << player << ". Picking any...\n";
  984. return pickHeroFor(false, player, town, available);
  985. }
  986. else
  987. {
  988. ret = pool[rand()%pool.size()];
  989. }
  990. }
  991. else
  992. {
  993. int sum=0, r;
  994. for(bmap<ui32, ConstTransitivePtr<CGHeroInstance> >::iterator i=available.begin(); i!=available.end(); i++)
  995. {
  996. if(pavailable.find(i->first)->second & 1<<player
  997. && !bannedClass || i->second->type->heroClass != bannedClass)
  998. {
  999. pool.push_back(i->second);
  1000. sum += i->second->type->heroClass->selectionProbability[town->typeID]; //total weight
  1001. }
  1002. }
  1003. if(!pool.size())
  1004. {
  1005. tlog1 << "There are no heroes available for player " << player<<"!\n";
  1006. return NULL;
  1007. }
  1008. r = rand()%sum;
  1009. for (unsigned int i=0; i<pool.size(); i++)
  1010. {
  1011. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  1012. if(r < 0)
  1013. {
  1014. ret = pool[i];
  1015. break;
  1016. }
  1017. }
  1018. if(!ret)
  1019. ret = pool.back();
  1020. }
  1021. available.erase(ret->subID);
  1022. return ret;
  1023. }
  1024. //void CGameState::apply(CPack * pack)
  1025. //{
  1026. // while(!mx->try_lock())
  1027. // boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  1028. // //applyNL(pack);
  1029. // mx->unlock();
  1030. //}
  1031. int CGameState::pickHero(int owner)
  1032. {
  1033. int h=-1;
  1034. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  1035. if(!map->getHero(h = ps.hero,0) && h>=0) //we haven't used selected hero
  1036. return h;
  1037. int i=0;
  1038. do //try to find free hero of our faction
  1039. {
  1040. i++;
  1041. h = ps.castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  1042. } while( map->getHero(h) && i<175);
  1043. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  1044. {
  1045. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  1046. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  1047. if(!map->getHero(j))
  1048. h=j;
  1049. }
  1050. return h;
  1051. }
  1052. CGHeroInstance *CGameState::getHero(int objid)
  1053. {
  1054. if(objid<0 || objid>=map->objects.size() || map->objects[objid]->ID!=HEROI_TYPE)
  1055. return NULL;
  1056. return static_cast<CGHeroInstance *>(map->objects[objid].get());
  1057. }
  1058. const CGHeroInstance * CGameState::getHero( int objid ) const
  1059. {
  1060. return (const_cast<CGameState *>(this))->getHero(objid);
  1061. }
  1062. CGTownInstance *CGameState::getTown(int objid)
  1063. {
  1064. if(objid<0 || objid>=map->objects.size())
  1065. return NULL;
  1066. CGObjectInstance *obj = map->objects[objid];
  1067. if(obj->ID != TOWNI_TYPE)
  1068. return NULL;
  1069. return static_cast<CGTownInstance *>(obj);
  1070. }
  1071. const CGTownInstance * CGameState::getTown( int objid ) const
  1072. {
  1073. return (const_cast<CGameState *>(this))->getTown(objid);
  1074. }
  1075. std::pair<int,int> CGameState::pickObject (CGObjectInstance *obj)
  1076. {
  1077. switch(obj->ID)
  1078. {
  1079. case 65:
  1080. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR | CArtifact::ART_RELIC));
  1081. case 66: //random treasure artifact
  1082. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_TREASURE));
  1083. case 67: //random minor artifact
  1084. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_MINOR));
  1085. case 68: //random major artifact
  1086. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_MAJOR));
  1087. case 69: //random relic artifact
  1088. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_RELIC));
  1089. case 70: //random hero
  1090. {
  1091. return std::pair<int,int>(HEROI_TYPE,pickHero(obj->tempOwner));
  1092. }
  1093. case 71: //random monster
  1094. {
  1095. return std::pair<int,int>(54,VLC->creh->pickRandomMonster(boost::ref(ran)));
  1096. }
  1097. case 72: //random monster lvl1
  1098. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  1099. case 73: //random monster lvl2
  1100. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  1101. case 74: //random monster lvl3
  1102. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  1103. case 75: //random monster lvl4
  1104. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  1105. case 76: //random resource
  1106. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  1107. case 77: //random town
  1108. {
  1109. int align = (static_cast<CGTownInstance*>(obj))->alignment,
  1110. f;
  1111. if(align>PLAYER_LIMIT-1)//same as owner / random
  1112. {
  1113. if(obj->tempOwner > PLAYER_LIMIT-1)
  1114. f = -1; //random
  1115. else
  1116. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  1117. }
  1118. else
  1119. {
  1120. f = scenarioOps->getIthPlayersSettings(align).castle;
  1121. }
  1122. if(f<0) f = ran()%VLC->townh->towns.size();
  1123. return std::pair<int,int>(TOWNI_TYPE,f);
  1124. }
  1125. case 162: //random monster lvl5
  1126. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  1127. case 163: //random monster lvl6
  1128. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  1129. case 164: //random monster lvl7
  1130. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  1131. case 216: //random dwelling
  1132. {
  1133. int faction = ran()%F_NUMBER;
  1134. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  1135. CCreGen2ObjInfo* info = static_cast<CCreGen2ObjInfo*>(dwl->info);
  1136. if (info->asCastle)
  1137. {
  1138. for(unsigned int i=0;i<map->objects.size();i++)
  1139. {
  1140. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i].get())->identifier == info->identifier)
  1141. {
  1142. randomizeObject(map->objects[i]); //we have to randomize the castle first
  1143. faction = map->objects[i]->subID;
  1144. break;
  1145. }
  1146. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i].get())->identifier == info->identifier)
  1147. {
  1148. faction = map->objects[i]->subID;
  1149. break;
  1150. }
  1151. }
  1152. }
  1153. else
  1154. {
  1155. while((!(info->castles[0]&(1<<faction))))
  1156. {
  1157. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  1158. break;
  1159. faction = ran()%F_NUMBER;
  1160. }
  1161. }
  1162. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  1163. int cid = VLC->townh->towns[faction].basicCreatures[level];
  1164. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  1165. if(VLC->objh->cregens[i]==cid)
  1166. return std::pair<int,int>(17,i);
  1167. tlog3 << "Cannot find a dwelling for creature "<< cid << std::endl;
  1168. return std::pair<int,int>(17,0);
  1169. delete dwl->info;
  1170. dwl->info = NULL;
  1171. }
  1172. case 217:
  1173. {
  1174. int faction = ran()%F_NUMBER;
  1175. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  1176. CCreGenObjInfo* info = static_cast<CCreGenObjInfo*>(dwl->info);
  1177. if (info->asCastle)
  1178. {
  1179. for(unsigned int i=0;i<map->objects.size();i++)
  1180. {
  1181. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i].get())->identifier == info->identifier)
  1182. {
  1183. randomizeObject(map->objects[i]); //we have to randomize the castle first
  1184. faction = map->objects[i]->subID;
  1185. break;
  1186. }
  1187. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i].get())->identifier == info->identifier)
  1188. {
  1189. faction = map->objects[i]->subID;
  1190. break;
  1191. }
  1192. }
  1193. }
  1194. else
  1195. {
  1196. while((!(info->castles[0]&(1<<faction))))
  1197. {
  1198. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  1199. break;
  1200. faction = ran()%F_NUMBER;
  1201. }
  1202. }
  1203. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  1204. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  1205. if(VLC->objh->cregens[i]==cid)
  1206. return std::pair<int,int>(17,i);
  1207. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  1208. return std::pair<int,int>(17,0);
  1209. delete dwl->info;
  1210. dwl->info = NULL;
  1211. }
  1212. case 218:
  1213. {
  1214. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  1215. CCreGen3ObjInfo* info = static_cast<CCreGen3ObjInfo*>(dwl->info);
  1216. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  1217. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  1218. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  1219. if(VLC->objh->cregens[i]==cid)
  1220. return std::pair<int,int>(17,i);
  1221. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  1222. return std::pair<int,int>(17,0);
  1223. delete dwl->info;
  1224. dwl->info = NULL;
  1225. }
  1226. }
  1227. return std::pair<int,int>(-1,-1);
  1228. }
  1229. void CGameState::randomizeObject(CGObjectInstance *cur)
  1230. {
  1231. std::pair<int,int> ran = pickObject(cur);
  1232. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  1233. {
  1234. if(cur->ID==TOWNI_TYPE) //town - set def
  1235. {
  1236. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  1237. t->town = &VLC->townh->towns[t->subID];
  1238. if(t->hasCapitol())
  1239. t->defInfo = capitols[t->subID];
  1240. else if(t->hasFort())
  1241. t->defInfo = forts[t->subID];
  1242. else
  1243. t->defInfo = villages[t->subID];
  1244. }
  1245. return;
  1246. }
  1247. else if(ran.first==HEROI_TYPE)//special code for hero
  1248. {
  1249. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  1250. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  1251. cur->ID = ran.first;
  1252. h->portrait = cur->subID = ran.second;
  1253. h->type = VLC->heroh->heroes[ran.second];
  1254. h->randomizeArmy(h->type->heroType/2);
  1255. map->heroes.push_back(h);
  1256. return; //TODO: maybe we should do something with definfo?
  1257. }
  1258. else if(ran.first==TOWNI_TYPE)//special code for town
  1259. {
  1260. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  1261. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  1262. cur->ID = ran.first;
  1263. cur->subID = ran.second;
  1264. t->town = &VLC->townh->towns[ran.second];
  1265. if(t->hasCapitol())
  1266. t->defInfo = capitols[t->subID];
  1267. else if(t->hasFort())
  1268. t->defInfo = forts[t->subID];
  1269. else
  1270. t->defInfo = villages[t->subID];
  1271. t->randomizeArmy(t->subID);
  1272. map->towns.push_back(t);
  1273. return;
  1274. }
  1275. //we have to replace normal random object
  1276. cur->ID = ran.first;
  1277. cur->subID = ran.second;
  1278. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  1279. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  1280. if(!cur->defInfo)
  1281. {
  1282. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  1283. return;
  1284. }
  1285. map->addBlockVisTiles(cur);
  1286. }
  1287. int CGameState::getDate(int mode) const
  1288. {
  1289. int temp;
  1290. switch (mode)
  1291. {
  1292. case 0: //day number
  1293. return day;
  1294. break;
  1295. case 1: //day of week
  1296. temp = (day)%7; // 1 - Monday, 7 - Sunday
  1297. if (temp)
  1298. return temp;
  1299. else return 7;
  1300. break;
  1301. case 2: //current week
  1302. temp = ((day-1)/7)+1;
  1303. if (!(temp%4))
  1304. return 4;
  1305. else
  1306. return (temp%4);
  1307. break;
  1308. case 3: //current month
  1309. return ((day-1)/28)+1;
  1310. break;
  1311. case 4: //day of month
  1312. temp = (day)%28;
  1313. if (temp)
  1314. return temp;
  1315. else return 28;
  1316. break;
  1317. }
  1318. return 0;
  1319. }
  1320. CGameState::CGameState()
  1321. {
  1322. mx = new boost::shared_mutex();
  1323. map = NULL;
  1324. curB = NULL;
  1325. scenarioOps = NULL;
  1326. applierGs = new CApplier<CBaseForGSApply>;
  1327. registerTypes2(*applierGs);
  1328. objCaller = new CObjectCallersHandler;
  1329. campaign = NULL;
  1330. }
  1331. CGameState::~CGameState()
  1332. {
  1333. delete mx;
  1334. delete map;
  1335. delete curB;
  1336. //delete scenarioOps; //TODO: fix for loading ind delete
  1337. //delete initialOpts;
  1338. delete applierGs;
  1339. delete objCaller;
  1340. //TODO: delete properly that definfos
  1341. villages.clear();
  1342. capitols.clear();
  1343. }
  1344. namespace CGH
  1345. {
  1346. using namespace std;
  1347. static void readItTo(ifstream & input, vector< vector<int> > & dest) //reads 7 lines, i-th one containing i integers, and puts it to dest
  1348. {
  1349. for(int j=0; j<7; ++j)
  1350. {
  1351. std::vector<int> pom;
  1352. for(int g=0; g<j+1; ++g)
  1353. {
  1354. int hlp; input>>hlp;
  1355. pom.push_back(hlp);
  1356. }
  1357. dest.push_back(pom);
  1358. }
  1359. }
  1360. }
  1361. BattleInfo * setupBattle( int3 tile, int terrain, int terType, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town )
  1362. {
  1363. CMP_stack cmpst;
  1364. BattleInfo *curB = new BattleInfo;
  1365. curB->side1 = armies[0]->tempOwner;
  1366. curB->side2 = armies[1]->tempOwner;
  1367. if(curB->side2 == 254)
  1368. curB->side2 = 255;
  1369. std::vector<CStack*> & stacks = (curB->stacks);
  1370. curB->tile = tile;
  1371. curB->battlefieldType = terType;
  1372. curB->belligerents[0] = const_cast<CArmedInstance*>(armies[0]);
  1373. curB->belligerents[1] = const_cast<CArmedInstance*>(armies[1]);
  1374. curB->heroes[0] = const_cast<CGHeroInstance*>(heroes[0]);
  1375. curB->heroes[1] = const_cast<CGHeroInstance*>(heroes[1]);
  1376. curB->round = -2;
  1377. curB->activeStack = -1;
  1378. if(town)
  1379. {
  1380. curB->tid = town->id;
  1381. curB->siege = town->fortLevel();
  1382. }
  1383. else
  1384. {
  1385. curB->tid = -1;
  1386. curB->siege = 0;
  1387. }
  1388. //reading battleStartpos
  1389. std::ifstream positions;
  1390. positions.open(DATA_DIR "/config/battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  1391. if(!positions.is_open())
  1392. {
  1393. tlog1<<"Unable to open battleStartpos.txt!"<<std::endl;
  1394. }
  1395. std::string dump;
  1396. positions>>dump; positions>>dump;
  1397. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight, attackerCreBank, defenderCreBank;
  1398. CGH::readItTo(positions, attackerLoose);
  1399. positions>>dump;
  1400. CGH::readItTo(positions, defenderLoose);
  1401. positions>>dump;
  1402. positions>>dump;
  1403. CGH::readItTo(positions, attackerTight);
  1404. positions>>dump;
  1405. CGH::readItTo(positions, defenderTight);
  1406. positions>>dump;
  1407. positions>>dump;
  1408. CGH::readItTo(positions, attackerCreBank);
  1409. positions>>dump;
  1410. CGH::readItTo(positions, defenderCreBank);
  1411. positions.close();
  1412. //battleStartpos read
  1413. int k = 0; //stack serial
  1414. for(TSlots::const_iterator i = armies[0]->Slots().begin(); i!=armies[0]->Slots().end(); i++, k++)
  1415. {
  1416. int pos;
  1417. if(creatureBank)
  1418. pos = attackerCreBank[armies[0]->stacksCount()-1][k];
  1419. else if(armies[0]->formation)
  1420. pos = attackerTight[armies[0]->stacksCount()-1][k];
  1421. else
  1422. pos = attackerLoose[armies[0]->stacksCount()-1][k];
  1423. CStack * stack = curB->generateNewStack(*i->second, stacks.size(), true, i->first, pos);
  1424. stacks.push_back(stack);
  1425. }
  1426. k = 0;
  1427. for(TSlots::const_iterator i = armies[1]->Slots().begin(); i!=armies[1]->Slots().end(); i++, k++)
  1428. {
  1429. int pos;
  1430. if(creatureBank)
  1431. pos = defenderCreBank[armies[1]->stacksCount()-1][k];
  1432. else if(armies[1]->formation)
  1433. pos = defenderTight[armies[1]->stacksCount()-1][k];
  1434. else
  1435. pos = defenderLoose[armies[1]->stacksCount()-1][k];
  1436. CStack * stack = curB->generateNewStack(*i->second, stacks.size(), false, i->first, pos);
  1437. stacks.push_back(stack);
  1438. }
  1439. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  1440. {
  1441. if((stacks[g]->position%17)==1 && stacks[g]->doubleWide() && stacks[g]->attackerOwned)
  1442. {
  1443. stacks[g]->position += 1;
  1444. }
  1445. else if((stacks[g]->position%17)==15 && stacks[g]->doubleWide() && !stacks[g]->attackerOwned)
  1446. {
  1447. stacks[g]->position -= 1;
  1448. }
  1449. }
  1450. //adding war machines
  1451. if(heroes[0])
  1452. {
  1453. if(heroes[0]->getArt(13)) //ballista
  1454. {
  1455. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(146, 1), stacks.size(), true, 255, 52);
  1456. stacks.push_back(stack);
  1457. }
  1458. if(heroes[0]->getArt(14)) //ammo cart
  1459. {
  1460. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(148, 1), stacks.size(), true, 255, 18);
  1461. stacks.push_back(stack);
  1462. }
  1463. if(heroes[0]->getArt(15)) //first aid tent
  1464. {
  1465. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(147, 1), stacks.size(), true, 255, 154);
  1466. stacks.push_back(stack);
  1467. }
  1468. }
  1469. if(heroes[1])
  1470. {
  1471. //defending hero shouldn't receive ballista (bug #551)
  1472. if(heroes[1]->getArt(13) && !town) //ballista
  1473. {
  1474. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(146, 1), stacks.size(), false, 255, 66);
  1475. stacks.push_back(stack);
  1476. }
  1477. if(heroes[1]->getArt(14)) //ammo cart
  1478. {
  1479. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(148, 1), stacks.size(), false, 255, 32);
  1480. stacks.push_back(stack);
  1481. }
  1482. if(heroes[1]->getArt(15)) //first aid tent
  1483. {
  1484. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(147, 1), stacks.size(), false, 255, 168);
  1485. stacks.push_back(stack);
  1486. }
  1487. }
  1488. if(town && heroes[0] && town->hasFort()) //catapult
  1489. {
  1490. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(145, 1), stacks.size(), true, 255, 120);
  1491. stacks.push_back(stack);
  1492. }
  1493. //war machines added
  1494. switch(curB->siege) //adding towers
  1495. {
  1496. case 3: //castle
  1497. {//lower tower / upper tower
  1498. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), stacks.size(), false, 255, -4);
  1499. stacks.push_back(stack);
  1500. stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), stacks.size(), false, 255, -3);
  1501. stacks.push_back(stack);
  1502. }
  1503. case 2: //citadel
  1504. {//main tower
  1505. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), stacks.size(), false, 255, -2);
  1506. stacks.push_back(stack);
  1507. }
  1508. }
  1509. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1510. //seting up siege
  1511. if(town && town->hasFort())
  1512. {
  1513. for(int b=0; b<ARRAY_COUNT(curB->si.wallState); ++b)
  1514. {
  1515. curB->si.wallState[b] = 1;
  1516. }
  1517. }
  1518. //randomize obstacles
  1519. if(town == NULL && !creatureBank) //do it only when it's not siege and not creature bank
  1520. {
  1521. bool obAv[BFIELD_SIZE]; //availability of hexes for obstacles;
  1522. std::vector<int> possibleObstacles;
  1523. for(int i=0; i<BFIELD_SIZE; ++i)
  1524. {
  1525. if(i%17 < 4 || i%17 > 12)
  1526. {
  1527. obAv[i] = false;
  1528. }
  1529. else
  1530. {
  1531. obAv[i] = true;
  1532. }
  1533. }
  1534. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  1535. {
  1536. if(g->second.allowedTerrains[terType-1] == '1') //we need to take terType with -1 because terrain ids start from 1 and allowedTerrains array is indexed from 0
  1537. {
  1538. possibleObstacles.push_back(g->first);
  1539. }
  1540. }
  1541. srand(time(NULL));
  1542. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  1543. {
  1544. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  1545. while(toBlock>0)
  1546. {
  1547. CObstacleInstance coi;
  1548. coi.uniqueID = curB->obstacles.size();
  1549. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  1550. coi.pos = rand()%BFIELD_SIZE;
  1551. std::vector<int> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  1552. bool badObstacle = false;
  1553. for(int b=0; b<block.size(); ++b)
  1554. {
  1555. if(block[b] < 0 || block[b] >= BFIELD_SIZE || !obAv[block[b]])
  1556. {
  1557. badObstacle = true;
  1558. break;
  1559. }
  1560. }
  1561. if(badObstacle) continue;
  1562. //obstacle can be placed
  1563. curB->obstacles.push_back(coi);
  1564. for(int b=0; b<block.size(); ++b)
  1565. {
  1566. if(block[b] >= 0 && block[b] < BFIELD_SIZE)
  1567. obAv[block[b]] = false;
  1568. }
  1569. toBlock -= block.size();
  1570. }
  1571. }
  1572. }
  1573. // //giving building bonuses, if siege and we have harrisoned hero
  1574. // if (town)
  1575. // {
  1576. // if (heroes[1])
  1577. // {
  1578. // for (int i=0; i<4; i++)
  1579. // {
  1580. // int val = town->defenceBonus(i);
  1581. // if (val)
  1582. // {
  1583. // GiveBonus gs;
  1584. // gs.bonus = Bonus(Bonus::ONE_BATTLE, Bonus::PRIMARY_SKILL, Bonus::OBJECT, val, -1, "", i);
  1585. // gs.id = heroes[1]->id;
  1586. // sendAndApply(&gs);
  1587. // }
  1588. // }
  1589. // }
  1590. // else//if we don't have hero - apply separately, if hero present - will be taken from hero bonuses
  1591. // {
  1592. // if(town->subID == 0 && vstd::contains(town->builtBuildings,22)) //castle, brotherhood of sword built
  1593. // for(int g=0; g<stacks.size(); ++g)
  1594. // stacks[g]->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 2, Bonus::TOWN_STRUCTURE));
  1595. //
  1596. // else if(vstd::contains(town->builtBuildings,5)) //tavern is built
  1597. // for(int g=0; g<stacks.size(); ++g)
  1598. // stacks[g]->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 1, Bonus::TOWN_STRUCTURE));
  1599. //
  1600. // if(town->subID == 1 && vstd::contains(town->builtBuildings,21)) //rampart, fountain of fortune is present
  1601. // for(int g=0; g<stacks.size(); ++g)
  1602. // stacks[g]->addNewBonus(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, 2, Bonus::TOWN_STRUCTURE));
  1603. // }
  1604. // }
  1605. //giving terrain overalay premies
  1606. int bonusSubtype = -1;
  1607. switch(terType)
  1608. {
  1609. case 9: //magic plains
  1610. {
  1611. bonusSubtype = 0;
  1612. }
  1613. case 14: //fiery fields
  1614. {
  1615. if(bonusSubtype == -1) bonusSubtype = 1;
  1616. }
  1617. case 15: //rock lands
  1618. {
  1619. if(bonusSubtype == -1) bonusSubtype = 8;
  1620. }
  1621. case 16: //magic clouds
  1622. {
  1623. if(bonusSubtype == -1) bonusSubtype = 2;
  1624. }
  1625. case 17: //lucid pools
  1626. {
  1627. if(bonusSubtype == -1) bonusSubtype = 4;
  1628. }
  1629. { //common part for cases 9, 14, 15, 16, 17
  1630. curB->addNewBonus(new Bonus(Bonus::ONE_BATTLE, Bonus::MAGIC_SCHOOL_SKILL, Bonus::TERRAIN_OVERLAY, 3, -1, "", bonusSubtype));
  1631. break;
  1632. }
  1633. case 18: //holy ground
  1634. {
  1635. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(GOOD)));
  1636. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(EVIL)));
  1637. break;
  1638. }
  1639. case 19: //clover field
  1640. { //+2 luck bonus for neutral creatures
  1641. curB->addNewBonus(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, +2, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureFactionLimiter(-1)));
  1642. break;
  1643. }
  1644. case 20: //evil fog
  1645. {
  1646. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(GOOD)));
  1647. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(EVIL)));
  1648. break;
  1649. }
  1650. case 22: //cursed ground
  1651. {
  1652. curB->addNewBonus(makeFeature(Bonus::NO_MORALE, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1653. curB->addNewBonus(makeFeature(Bonus::NO_LUCK, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1654. curB->addNewBonus(makeFeature(Bonus::BLOCK_SPELLS_ABOVE_LEVEL, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_OVERLAY));
  1655. break;
  1656. }
  1657. }
  1658. //overlay premies given
  1659. //native terrain bonuses
  1660. if(town) //during siege always take premies for native terrain of faction
  1661. terrain = VLC->heroh->nativeTerrains[town->town->typeID];
  1662. ILimiter *nativeTerrain = new CreatureNativeTerrainLimiter(terrain);
  1663. curB->addNewBonus(makeFeature(Bonus::STACKS_SPEED, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1664. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::ATTACK, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1665. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::DEFENSE, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1666. //////////////////////////////////////////////////////////////////////////
  1667. return curB;
  1668. }
  1669. BattleInfo * CGameState::setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town)
  1670. {
  1671. int terrain = map->getTile(tile).tertype;
  1672. int terType = battleGetBattlefieldType(tile);
  1673. return ::setupBattle(tile, terrain, terType, armies, heroes, creatureBank, town);
  1674. }
  1675. void CGameState::init( StartInfo * si, ui32 checksum, int Seed )
  1676. {
  1677. struct HLP
  1678. {
  1679. //it's assumed that given hero should receive the bonus
  1680. static void giveCampaignBonusToHero(CGHeroInstance * hero, const StartInfo * si, const CScenarioTravel & st )
  1681. {
  1682. const CScenarioTravel::STravelBonus & curBonus = st.bonusesToChoose[si->choosenCampaignBonus];
  1683. if(curBonus.isBonusForHero())
  1684. {
  1685. //apply bonus
  1686. switch (curBonus.type)
  1687. {
  1688. case 0: //spell
  1689. hero->spells.insert(curBonus.info2);
  1690. break;
  1691. case 1: //monster
  1692. {
  1693. for(int i=0; i<ARMY_SIZE; i++)
  1694. {
  1695. if(hero->slotEmpty(i))
  1696. {
  1697. hero->addToSlot(i, curBonus.info2, curBonus.info3);
  1698. break;
  1699. }
  1700. }
  1701. }
  1702. break;
  1703. case 3: //artifact
  1704. hero->giveArtifact(curBonus.info2);
  1705. break;
  1706. case 4: //spell scroll
  1707. //TODO
  1708. break;
  1709. case 5: //prim skill
  1710. {
  1711. const ui8* ptr = reinterpret_cast<const ui8*>(&curBonus.info2);
  1712. for (int g=0; g<PRIMARY_SKILLS; ++g)
  1713. {
  1714. int val = ptr[g];
  1715. if (val == 0)
  1716. {
  1717. continue;
  1718. }
  1719. Bonus *bb = new Bonus(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::CAMPAIGN_BONUS, val, si->whichMapInCampaign, g);
  1720. hero->addNewBonus(bb);
  1721. }
  1722. }
  1723. break;
  1724. case 6: //sec skills
  1725. hero->setSecSkillLevel(static_cast<CGHeroInstance::SecondarySkill>(curBonus.info2), curBonus.info3, true);
  1726. break;
  1727. }
  1728. }
  1729. }
  1730. static std::vector<const PlayerSettings *> getHumanPlayerInfo(const StartInfo * si)
  1731. {
  1732. std::vector<const PlayerSettings *> ret;
  1733. for(std::map<int, PlayerSettings>::const_iterator it = si->playerInfos.begin();
  1734. it != si->playerInfos.end(); ++it)
  1735. {
  1736. if(it->second.human)
  1737. ret.push_back(&it->second);
  1738. }
  1739. return ret;
  1740. }
  1741. static void replaceHero( CGameState * gs, int objId, CGHeroInstance * ghi )
  1742. {
  1743. ghi->id = objId;
  1744. gs->map->objects[objId] = ghi;
  1745. gs->map->heroes.push_back(ghi);
  1746. }
  1747. //sort in descending order by power
  1748. static bool heroPowerSorter(const CGHeroInstance * a, const CGHeroInstance * b)
  1749. {
  1750. return a->getHeroStrength() > b->getHeroStrength();
  1751. }
  1752. };
  1753. seed = Seed;
  1754. ran.seed((boost::int32_t)seed);
  1755. VLC->creh->globalEffects = &globalEffects;
  1756. scenarioOps = new StartInfo(*si);
  1757. initialOpts = new StartInfo(*si);
  1758. si = NULL;
  1759. switch(scenarioOps->mode)
  1760. {
  1761. case StartInfo::NEW_GAME:
  1762. map = new Mapa(scenarioOps->mapname);
  1763. break;
  1764. case StartInfo::CAMPAIGN:
  1765. {
  1766. campaign = new CCampaignState();
  1767. campaign->initNewCampaign(*scenarioOps);
  1768. assert(vstd::contains(campaign->camp->mapPieces, scenarioOps->whichMapInCampaign));
  1769. std::string &mapContent = campaign->camp->mapPieces[scenarioOps->whichMapInCampaign];
  1770. map = new Mapa();
  1771. map->initFromBytes((const unsigned char*)mapContent.c_str());
  1772. }
  1773. break;
  1774. case StartInfo::DUEL:
  1775. {
  1776. int3 tile;
  1777. int terType = TerrainTile::grass;
  1778. int terrain = 15;
  1779. const CArmedInstance *armies[2];
  1780. const CGHeroInstance *heroes[2];
  1781. const CGTownInstance *town = NULL;
  1782. CGHeroInstance *h = new CGHeroInstance();
  1783. h->setOwner(0);
  1784. h->subID = 1;
  1785. h->initHero(1);
  1786. h->initObj();
  1787. //h->putStack(0, new CStackInstance(34, 5));
  1788. CGCreature *c = new CGCreature();
  1789. c->setOwner(1);
  1790. c->putStack(0, new CStackInstance(70, 6));
  1791. c->subID = 34;
  1792. c->initObj();
  1793. heroes[0] = h;
  1794. heroes[1] = NULL;
  1795. armies[0] = h;
  1796. armies[1] = c;
  1797. curB = ::setupBattle(tile, terrain, terType, armies, heroes, false, town);
  1798. curB->localInit();
  1799. return;
  1800. }
  1801. break;
  1802. default:
  1803. tlog1 << "Wrong mode: " << (int)scenarioOps->mode << std::endl;
  1804. return;
  1805. }
  1806. VLC->arth->initAllowedArtifactsList(map->allowedArtifact);
  1807. tlog0 << "Map loaded!" << std::endl;
  1808. //tlog0 <<"Reading and detecting map file (together): "<<tmh.getDif()<<std::endl;
  1809. if(checksum)
  1810. {
  1811. tlog0 << "\tServer checksum for " << scenarioOps->mapname <<": "<< checksum << std::endl;
  1812. tlog0 << "\tOur checksum for the map: "<< map->checksum << std::endl;
  1813. if(map->checksum != checksum)
  1814. {
  1815. tlog1 << "Wrong map checksum!!!" << std::endl;
  1816. throw std::string("Wrong checksum");
  1817. }
  1818. }
  1819. day = 0;
  1820. loadTownDInfos();
  1821. //pick grail location
  1822. if(map->grailPos.x < 0 || map->grailRadious) //grail not set or set within a radius around some place
  1823. {
  1824. if(!map->grailRadious) //radius not given -> anywhere on map
  1825. map->grailRadious = map->width * 2;
  1826. std::vector<int3> allowedPos;
  1827. // add all not blocked tiles in range
  1828. for (int i = 0; i < map->width ; i++)
  1829. {
  1830. for (int j = 0; j < map->height ; j++)
  1831. {
  1832. for (int k = 0; k <= map->twoLevel ; k++)
  1833. {
  1834. const TerrainTile &t = map->terrain[i][j][k];
  1835. if(!t.blocked
  1836. && !t.visitable
  1837. && t.tertype != TerrainTile::water
  1838. && t.tertype != TerrainTile::rock
  1839. && map->grailPos.dist2d(int3(i,j,k)) <= map->grailRadious)
  1840. allowedPos.push_back(int3(i,j,k));
  1841. }
  1842. }
  1843. }
  1844. //remove tiles with holes
  1845. for(unsigned int no=0; no<map->objects.size(); ++no)
  1846. if(map->objects[no]->ID == 124)
  1847. allowedPos -= map->objects[no]->pos;
  1848. if(allowedPos.size())
  1849. map->grailPos = allowedPos[ran() % allowedPos.size()];
  1850. else
  1851. tlog2 << "Warning: Grail cannot be placed, no appropriate tile found!\n";
  1852. }
  1853. //picking random factions for players
  1854. for(std::map<int, PlayerSettings>::iterator it = scenarioOps->playerInfos.begin();
  1855. it != scenarioOps->playerInfos.end(); ++it)
  1856. {
  1857. if(it->second.castle==-1)
  1858. {
  1859. int f;
  1860. do
  1861. {
  1862. f = ran()%F_NUMBER;
  1863. }while(!(map->players[it->first].allowedFactions & 1<<f));
  1864. it->second.castle = f;
  1865. }
  1866. }
  1867. //randomizing objects
  1868. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1869. {
  1870. randomizeObject(obj);
  1871. obj->hoverName = VLC->generaltexth->names[obj->ID];
  1872. //handle Favouring Winds - mark tiles under it
  1873. if(obj->ID == 225)
  1874. for (int i = 0; i < obj->getWidth() ; i++)
  1875. for (int j = 0; j < obj->getHeight() ; j++)
  1876. {
  1877. int3 pos = obj->pos - int3(i,j,0);
  1878. if(map->isInTheMap(pos))
  1879. map->getTile(pos).siodmyTajemniczyBajt |= 128;
  1880. }
  1881. }
  1882. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  1883. /*********creating players entries in gs****************************************/
  1884. for(std::map<int, PlayerSettings>::iterator it = scenarioOps->playerInfos.begin();
  1885. it != scenarioOps->playerInfos.end(); ++it)
  1886. {
  1887. std::pair<int,PlayerState> ins(it->first,PlayerState());
  1888. ins.second.color=ins.first;
  1889. ins.second.human = it->second.human;
  1890. ins.second.team = map->players[ins.first].team;
  1891. teams[ins.second.team].id = ins.second.team;//init team
  1892. teams[ins.second.team].players.insert(ins.first);//add player to team
  1893. players.insert(ins);
  1894. }
  1895. /*********give starting hero****************************************/
  1896. for(int i=0;i<PLAYER_LIMIT;i++)
  1897. {
  1898. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==CMapHeader::RoE))
  1899. {
  1900. int3 hpos = map->players[i].posOfMainTown;
  1901. hpos.x+=1;// hpos.y+=1;
  1902. if (scenarioOps->playerInfos.find(i) == scenarioOps->playerInfos.end())
  1903. {
  1904. continue;
  1905. }
  1906. int h=pickHero(i);
  1907. if(scenarioOps->playerInfos[i].hero == -1)
  1908. scenarioOps->playerInfos[i].hero = h;
  1909. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(HEROI_TYPE,h,hpos,i));
  1910. nnn->id = map->objects.size();
  1911. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  1912. for(unsigned int o=0;o<map->towns.size();o++) //find main town
  1913. {
  1914. if(map->towns[o]->pos == hpos)
  1915. {
  1916. map->towns[o]->visitingHero = nnn;
  1917. nnn->visitedTown = map->towns[o];
  1918. nnn->inTownGarrison = false;
  1919. break;
  1920. }
  1921. }
  1922. nnn->initHero();
  1923. map->heroes.push_back(nnn);
  1924. map->objects.push_back(nnn);
  1925. map->addBlockVisTiles(nnn);
  1926. //give campaign bonus
  1927. if (scenarioOps->mode == StartInfo::CAMPAIGN && getPlayer(nnn->tempOwner)->human)
  1928. {
  1929. HLP::giveCampaignBonusToHero(nnn, scenarioOps, campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions);
  1930. }
  1931. }
  1932. }
  1933. /*************************replace hero placeholders*****************************/
  1934. if (campaign)
  1935. {
  1936. CScenarioTravel::STravelBonus bonus =
  1937. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  1938. std::vector<CGHeroInstance *> Xheroes;
  1939. if (bonus.type == 8) //hero crossover
  1940. {
  1941. Xheroes = campaign->camp->scenarios[bonus.info2].crossoverHeroes;
  1942. }
  1943. //selecting heroes by type
  1944. for(int g=0; g<map->objects.size(); ++g)
  1945. {
  1946. CGObjectInstance * obj = map->objects[g];
  1947. if (obj->ID != 214) //not a placeholder
  1948. {
  1949. continue;
  1950. }
  1951. CGHeroPlaceholder * hp = static_cast<CGHeroPlaceholder*>(obj);
  1952. if(hp->subID != 0xFF) //select by type
  1953. {
  1954. bool found = false;
  1955. BOOST_FOREACH(CGHeroInstance * ghi, Xheroes)
  1956. {
  1957. if (ghi->subID == hp->subID)
  1958. {
  1959. found = true;
  1960. HLP::replaceHero(this, g, ghi);
  1961. Xheroes -= ghi;
  1962. break;
  1963. }
  1964. }
  1965. if (!found)
  1966. {
  1967. //TODO: create new hero of this type
  1968. }
  1969. }
  1970. }
  1971. //selecting heroes by power
  1972. std::sort(Xheroes.begin(), Xheroes.end(), HLP::heroPowerSorter);
  1973. for(int g=0; g<map->objects.size(); ++g)
  1974. {
  1975. CGObjectInstance * obj = map->objects[g];
  1976. if (obj->ID != 214) //not a placeholder
  1977. {
  1978. continue;
  1979. }
  1980. CGHeroPlaceholder * hp = static_cast<CGHeroPlaceholder*>(obj);
  1981. if (hp->subID == 0xFF) //select by power
  1982. {
  1983. if(Xheroes.size() > hp->power - 1)
  1984. HLP::replaceHero(this, g, Xheroes[hp->power - 1]);
  1985. else
  1986. tlog2 << "Warning, to hero to replace!\n";
  1987. //we don't have to remove hero from Xheroes because it would destroy the order and duplicates shouldn't happen
  1988. }
  1989. }
  1990. }
  1991. /******************RESOURCES****************************************************/
  1992. std::vector<int> startresAI, startresHuman;
  1993. std::ifstream tis(DATA_DIR "/config/startres.txt");
  1994. int k;
  1995. for (int j=0; j<scenarioOps->difficulty * 2; j++)
  1996. {
  1997. tis >> k;
  1998. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1999. tis>>k;
  2000. }
  2001. tis >> k;
  2002. for (int i=0; i<RESOURCE_QUANTITY; i++)
  2003. {
  2004. tis >> k;
  2005. startresHuman.push_back(k);
  2006. }
  2007. tis >> k;
  2008. for (int i=0; i<RESOURCE_QUANTITY; i++)
  2009. {
  2010. tis >> k;
  2011. startresAI.push_back(k);
  2012. }
  2013. tis.close();
  2014. tis.clear();
  2015. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  2016. {
  2017. (*i).second.resources.resize(RESOURCE_QUANTITY);
  2018. for (int x=0;x<RESOURCE_QUANTITY;x++)
  2019. {
  2020. if (i->second.human)
  2021. {
  2022. (*i).second.resources[x] = startresHuman[x];
  2023. }
  2024. else
  2025. {
  2026. (*i).second.resources[x] = startresAI[x];
  2027. }
  2028. }
  2029. }
  2030. //give start resource bonus in case of campaign
  2031. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  2032. {
  2033. CScenarioTravel::STravelBonus chosenBonus =
  2034. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  2035. if(chosenBonus.type == 7) //resource
  2036. {
  2037. std::vector<const PlayerSettings *> people = HLP::getHumanPlayerInfo(scenarioOps); //players we will give resource bonus
  2038. for (int b=0; b<people.size(); ++b)
  2039. {
  2040. std::vector<int> res; //resources we will give
  2041. switch (chosenBonus.info1)
  2042. {
  2043. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  2044. res.push_back(chosenBonus.info1);
  2045. break;
  2046. case 0xFD: //wood+ore
  2047. res.push_back(0); res.push_back(2);
  2048. break;
  2049. case 0xFE: //rare
  2050. res.push_back(1); res.push_back(3); res.push_back(4); res.push_back(5);
  2051. break;
  2052. default:
  2053. assert(0);
  2054. break;
  2055. }
  2056. //increasing resource quantity
  2057. for (int n=0; n<res.size(); ++n)
  2058. {
  2059. players[people[b]->color].resources[res[n]] += chosenBonus.info2;
  2060. }
  2061. }
  2062. }
  2063. }
  2064. /*************************HEROES************************************************/
  2065. std::set<int> hids; //hero ids to create pool
  2066. for(unsigned int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  2067. if(map->allowedHeroes[i])
  2068. hids.insert(i);
  2069. for (unsigned int i=0; i<map->heroes.size();i++) //heroes instances initialization
  2070. {
  2071. if (map->heroes[i]->getOwner()<0)
  2072. {
  2073. tlog2 << "Warning - hero with uninitialized owner!\n";
  2074. continue;
  2075. }
  2076. CGHeroInstance * vhi = (map->heroes[i]);
  2077. vhi->initHero();
  2078. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  2079. hids.erase(vhi->subID);
  2080. }
  2081. for (unsigned int i=0; i<map->objects.size();i++) //prisons
  2082. {
  2083. if (map->objects[i]->ID == 62)
  2084. hids.erase(map->objects[i]->subID);
  2085. }
  2086. for(unsigned int i=0; i<map->predefinedHeroes.size(); i++)
  2087. {
  2088. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  2089. continue;
  2090. map->predefinedHeroes[i]->initHero();
  2091. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  2092. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  2093. hids.erase(map->predefinedHeroes[i]->subID);
  2094. }
  2095. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go with default state into the pool
  2096. {
  2097. CGHeroInstance * vhi = new CGHeroInstance();
  2098. vhi->initHero(hid);
  2099. hpool.heroesPool[hid] = vhi;
  2100. hpool.pavailable[hid] = 0xff;
  2101. }
  2102. for(unsigned int i=0; i<map->disposedHeroes.size(); i++)
  2103. {
  2104. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  2105. }
  2106. if (scenarioOps->mode == StartInfo::CAMPAIGN) //give campaign bonuses for specific / best hero
  2107. {
  2108. CScenarioTravel::STravelBonus chosenBonus =
  2109. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  2110. if (chosenBonus.isBonusForHero() && chosenBonus.info1 != 0xFFFE) //exclude generated heroes
  2111. {
  2112. //find human player
  2113. int humanPlayer;
  2114. for (std::map<ui8, PlayerState>::iterator it=players.begin(); it != players.end(); ++it)
  2115. {
  2116. if(it->second.human)
  2117. {
  2118. humanPlayer = it->first;
  2119. break;
  2120. }
  2121. }
  2122. std::vector<ConstTransitivePtr<CGHeroInstance> > & heroes = players[humanPlayer].heroes;
  2123. if (chosenBonus.info1 == 0xFFFD) //most powerful
  2124. {
  2125. int maxB = -1;
  2126. for (int b=0; b<heroes.size(); ++b)
  2127. {
  2128. if (maxB == -1 || heroes[b]->getTotalStrength() > heroes[maxB]->getTotalStrength())
  2129. {
  2130. maxB = b;
  2131. }
  2132. }
  2133. if(maxB < 0)
  2134. tlog2 << "Warning - cannot give bonus to hero cause there are no heroes!\n";
  2135. else
  2136. HLP::giveCampaignBonusToHero(heroes[maxB], scenarioOps, campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions);
  2137. }
  2138. else //specific hero
  2139. {
  2140. for (int b=0; b<heroes.size(); ++b)
  2141. {
  2142. if (heroes[b]->subID == chosenBonus.info1)
  2143. {
  2144. HLP::giveCampaignBonusToHero(heroes[b], scenarioOps, campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions);
  2145. break;
  2146. }
  2147. }
  2148. }
  2149. }
  2150. }
  2151. /*************************FOG**OF**WAR******************************************/
  2152. for(std::map<ui8, TeamState>::iterator k=teams.begin(); k!=teams.end(); ++k)
  2153. {
  2154. k->second.fogOfWarMap.resize(map->width);
  2155. for(int g=0; g<map->width; ++g)
  2156. k->second.fogOfWarMap[g].resize(map->height);
  2157. for(int g=-0; g<map->width; ++g)
  2158. for(int h=0; h<map->height; ++h)
  2159. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  2160. for(int g=0; g<map->width; ++g)
  2161. for(int h=0; h<map->height; ++h)
  2162. for(int v=0; v<map->twoLevel+1; ++v)
  2163. k->second.fogOfWarMap[g][h][v] = 0;
  2164. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  2165. {
  2166. if( !vstd::contains(k->second.players, obj->tempOwner)) continue; //not a flagged object
  2167. std::set<int3> tiles;
  2168. obj->getSightTiles(tiles);
  2169. BOOST_FOREACH(int3 tile, tiles)
  2170. {
  2171. k->second.fogOfWarMap[tile.x][tile.y][tile.z] = 1;
  2172. }
  2173. }
  2174. }
  2175. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  2176. {
  2177. //starting bonus
  2178. if(scenarioOps->playerInfos[k->first].bonus==PlayerSettings::brandom)
  2179. scenarioOps->playerInfos[k->first].bonus = ran()%3;
  2180. switch(scenarioOps->playerInfos[k->first].bonus)
  2181. {
  2182. case PlayerSettings::bgold:
  2183. k->second.resources[6] += 500 + (ran()%6)*100;
  2184. break;
  2185. case PlayerSettings::bresource:
  2186. {
  2187. int res = VLC->townh->towns[scenarioOps->playerInfos[k->first].castle].primaryRes;
  2188. if(res == 127)
  2189. {
  2190. k->second.resources[0] += 5 + ran()%6;
  2191. k->second.resources[2] += 5 + ran()%6;
  2192. }
  2193. else
  2194. {
  2195. k->second.resources[res] += 3 + ran()%4;
  2196. }
  2197. break;
  2198. }
  2199. case PlayerSettings::bartifact:
  2200. {
  2201. if(!k->second.heroes.size())
  2202. {
  2203. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  2204. break;
  2205. }
  2206. CArtifact *toGive;
  2207. toGive = VLC->arth->artifacts[VLC->arth->getRandomArt (CArtifact::ART_TREASURE)];
  2208. CGHeroInstance *hero = k->second.heroes[0];
  2209. std::vector<ui16>::iterator slot = vstd::findFirstNot (hero->artifWorn, toGive->possibleSlots);
  2210. if(slot != toGive->possibleSlots.end())
  2211. VLC->arth->equipArtifact(hero->artifWorn, *slot, toGive);
  2212. else
  2213. hero->giveArtifact(toGive->id);
  2214. }
  2215. }
  2216. }
  2217. /****************************TOWNS************************************************/
  2218. for ( int i=0; i<4; i++)
  2219. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  2220. for (unsigned int i=0;i<map->towns.size();i++)
  2221. {
  2222. CGTownInstance * vti =(map->towns[i]);
  2223. if(!vti->town)
  2224. vti->town = &VLC->townh->towns[vti->subID];
  2225. if (vti->name.length()==0) // if town hasn't name we draw it
  2226. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  2227. //init buildings
  2228. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  2229. {
  2230. vti->builtBuildings.erase(-50);
  2231. vti->builtBuildings.insert(10);
  2232. vti->builtBuildings.insert(5);
  2233. vti->builtBuildings.insert(30);
  2234. if(ran()%2)
  2235. vti->builtBuildings.insert(31);
  2236. }
  2237. if (vstd::contains(vti->builtBuildings,(6)) && vti->state()==2)
  2238. vti->builtBuildings.erase(6);//if we have harbor without water - erase it (this is H3 behaviour)
  2239. //init hordes
  2240. for (int i = 0; i<CREATURES_PER_TOWN; i++)
  2241. if (vstd::contains(vti->builtBuildings,(-31-i))) //if we have horde for this level
  2242. {
  2243. vti->builtBuildings.erase(-31-i);//remove old ID
  2244. if (vti->town->hordeLvl[0] == i)//if town first horde is this one
  2245. {
  2246. vti->builtBuildings.insert(18);//add it
  2247. if (vstd::contains(vti->builtBuildings,(37+i)))//if we have upgraded dwelling as well
  2248. vti->builtBuildings.insert(19);//add it as well
  2249. }
  2250. if (vti->town->hordeLvl[1] == i)//if town second horde is this one
  2251. {
  2252. vti->builtBuildings.insert(24);
  2253. if (vstd::contains(vti->builtBuildings,(37+i)))
  2254. vti->builtBuildings.insert(25);
  2255. }
  2256. }
  2257. for (std::list<CCastleEvent*>::iterator ev=vti->events.begin(); ev!=vti->events.end(); ev++)
  2258. for (int i = 0; i<CREATURES_PER_TOWN; i++)
  2259. if (vstd::contains((*ev)->buildings,(-31-i))) //if we have horde for this level
  2260. {
  2261. (*ev)->buildings.erase(-31-i);
  2262. if (vti->town->hordeLvl[0] == i)
  2263. (*ev)->buildings.insert(18);
  2264. if (vti->town->hordeLvl[1] == i)
  2265. (*ev)->buildings.insert(24);
  2266. }
  2267. //init spells
  2268. vti->spells.resize(SPELL_LEVELS);
  2269. CSpell *s;
  2270. for(unsigned int z=0; z<vti->obligatorySpells.size();z++)
  2271. {
  2272. s = VLC->spellh->spells[vti->obligatorySpells[z]];
  2273. vti->spells[s->level-1].push_back(s->id);
  2274. vti->possibleSpells -= s->id;
  2275. }
  2276. while(vti->possibleSpells.size())
  2277. {
  2278. ui32 total=0;
  2279. int sel = -1;
  2280. for(unsigned int ps=0;ps<vti->possibleSpells.size();ps++)
  2281. total += VLC->spellh->spells[vti->possibleSpells[ps]]->probabilities[vti->subID];
  2282. int r = (total)? ran()%total : -1;
  2283. for(unsigned int ps=0; ps<vti->possibleSpells.size();ps++)
  2284. {
  2285. r -= VLC->spellh->spells[vti->possibleSpells[ps]]->probabilities[vti->subID];
  2286. if(r<0)
  2287. {
  2288. sel = ps;
  2289. break;
  2290. }
  2291. }
  2292. if(sel<0)
  2293. sel=0;
  2294. CSpell *s = VLC->spellh->spells[vti->possibleSpells[sel]];
  2295. vti->spells[s->level-1].push_back(s->id);
  2296. vti->possibleSpells -= s->id;
  2297. }
  2298. if(vti->getOwner() != 255)
  2299. getPlayer(vti->getOwner())->towns.push_back(vti);
  2300. }
  2301. //campaign bonuses for towns
  2302. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  2303. {
  2304. CScenarioTravel::STravelBonus chosenBonus =
  2305. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  2306. if (chosenBonus.type == 2)
  2307. {
  2308. for (int g=0; g<map->towns.size(); ++g)
  2309. {
  2310. PlayerState * owner = getPlayer(map->towns[g]->getOwner());
  2311. PlayerInfo & pi = map->players[owner->color];
  2312. if (owner->human && //human-owned
  2313. map->towns[g]->pos == pi.posOfMainTown + int3(2, 0, 0))
  2314. {
  2315. map->towns[g]->builtBuildings.insert(
  2316. CBuildingHandler::campToERMU(chosenBonus.info1, map->towns[g]->town->typeID, map->towns[g]->builtBuildings));
  2317. break;
  2318. }
  2319. }
  2320. }
  2321. }
  2322. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  2323. {
  2324. if(k->first==-1 || k->first==255)
  2325. continue;
  2326. //init visiting and garrisoned heroes
  2327. for(unsigned int l=0; l<k->second.heroes.size();l++)
  2328. {
  2329. CGHeroInstance *h = k->second.heroes[l];
  2330. for(unsigned int m=0; m<k->second.towns.size();m++)
  2331. {
  2332. CGTownInstance *t = k->second.towns[m];
  2333. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  2334. if(vistile == h->pos || h->pos==t->pos)
  2335. {
  2336. t->visitingHero = h;
  2337. h->visitedTown = t;
  2338. h->inTownGarrison = false;
  2339. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  2340. {
  2341. map->removeBlockVisTiles(h);
  2342. h->pos.x -= 1;
  2343. map->addBlockVisTiles(h);
  2344. }
  2345. break;
  2346. }
  2347. }
  2348. }
  2349. }
  2350. objCaller->preInit();
  2351. for(unsigned int i=0; i<map->objects.size(); i++)
  2352. {
  2353. map->objects[i]->initObj();
  2354. if(map->objects[i]->ID == 62) //prison also needs to initialize hero
  2355. static_cast<CGHeroInstance*>(map->objects[i].get())->initHero();
  2356. }
  2357. CGTeleport::postInit(); //pairing subterranean gates
  2358. }
  2359. bool CGameState::battleCanFlee(int player)
  2360. {
  2361. if(!curB) //there is no battle
  2362. return false;
  2363. if (player == curB->side1)
  2364. {
  2365. if (!curB->heroes[0])
  2366. return false;//current player have no hero
  2367. }
  2368. else
  2369. {
  2370. if (!curB->heroes[1])
  2371. return false;
  2372. }
  2373. if( ( curB->heroes[0] && curB->heroes[0]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE) ) //eg. one of heroes is wearing shakles of war
  2374. || ( curB->heroes[1] && curB->heroes[1]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE)))
  2375. return false;
  2376. if (player == curB->side2 && curB->siege //defender in siege
  2377. && !(getTown(curB->tid)->subID == 6 && vstd::contains(getTown(curB->tid)->builtBuildings, 17)))//without escape tunnel
  2378. return false;
  2379. return true;
  2380. }
  2381. int CGameState::battleGetStack(int pos, bool onlyAlive)
  2382. {
  2383. if(!curB)
  2384. return -1;
  2385. for(unsigned int g=0; g<curB->stacks.size(); ++g)
  2386. {
  2387. if((curB->stacks[g]->position == pos
  2388. || (curB->stacks[g]->doubleWide()
  2389. &&( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos)
  2390. || (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos) )
  2391. ))
  2392. && (!onlyAlive || curB->stacks[g]->alive())
  2393. )
  2394. return curB->stacks[g]->ID;
  2395. }
  2396. return -1;
  2397. }
  2398. int CGameState::battleGetBattlefieldType(int3 tile)
  2399. {
  2400. if(tile==int3() && curB)
  2401. tile = curB->tile;
  2402. else if(tile==int3() && !curB)
  2403. return -1;
  2404. const TerrainTile &t = map->getTile(tile);
  2405. //fight in mine -> subterranean
  2406. if(dynamic_cast<const CGMine *>(t.visitableObjects.front()))
  2407. return 12;
  2408. const std::vector <ConstTransitivePtr<CGObjectInstance> > & objs = map->objects;
  2409. for(int g=0; g<objs.size(); ++g)
  2410. {
  2411. if( !objs[g] || objs[g]->pos.x - tile.x < 0 || objs[g]->pos.x - tile.x >= 8
  2412. || tile.y - objs[g]->pos.y + 5 < 0 || tile.y - objs[g]->pos.y + 5 >=6
  2413. || !objs[g]->coveringAt(objs[g]->pos.x - tile.x, tile.y - objs[g]->pos.y + 5)
  2414. ) //look only for objects covering given tile
  2415. continue;
  2416. switch(objs[g]->ID)
  2417. {
  2418. case 222: //clover field
  2419. return 19;
  2420. case 21: case 223: //cursed ground
  2421. return 22;
  2422. case 224: //evil fog
  2423. return 20;
  2424. case 225: //favourable winds
  2425. return 21;
  2426. case 226: //fiery fields
  2427. return 14;
  2428. case 227: //holy ground
  2429. return 18;
  2430. case 228: //lucid pools
  2431. return 17;
  2432. case 229: //magic clouds
  2433. return 16;
  2434. case 46: case 230: //magic plains
  2435. return 9;
  2436. case 231: //rocklands
  2437. return 15;
  2438. }
  2439. }
  2440. switch(t.tertype)
  2441. {
  2442. case TerrainTile::dirt:
  2443. return rand()%3+3;
  2444. case TerrainTile::sand:
  2445. return 2; //TODO: coast support
  2446. case TerrainTile::grass:
  2447. return rand()%2+6;
  2448. case TerrainTile::snow:
  2449. return rand()%2+10;
  2450. case TerrainTile::swamp:
  2451. return 13;
  2452. case TerrainTile::rough:
  2453. return 23;
  2454. case TerrainTile::subterranean:
  2455. return 12;
  2456. case TerrainTile::lava:
  2457. return 8;
  2458. case TerrainTile::water:
  2459. return 25;
  2460. case TerrainTile::rock:
  2461. return 15;
  2462. default:
  2463. return -1;
  2464. }
  2465. }
  2466. const CGHeroInstance * CGameState::battleGetOwner(int stackID)
  2467. {
  2468. if(!curB)
  2469. return NULL;
  2470. return curB->heroes[!curB->getStack(stackID)->attackerOwned];
  2471. }
  2472. std::set<std::pair<int, int> > costDiff(const std::vector<ui32> &a, const std::vector<ui32> &b, const int modifier = 100) //modifer %
  2473. {
  2474. std::set<std::pair<int, int> > ret;
  2475. for(int j=0;j<RESOURCE_QUANTITY;j++)
  2476. {
  2477. assert(a[j] >= b[j]);
  2478. if(int dif = modifier * (a[j] - b[j]) / 100)
  2479. ret.insert(std::make_pair(j,dif));
  2480. }
  2481. return ret;
  2482. }
  2483. UpgradeInfo CGameState::getUpgradeInfo(const CStackInstance &stack)
  2484. {
  2485. UpgradeInfo ret;
  2486. const CCreature *base = stack.type;
  2487. const CGHeroInstance *h = stack.armyObj->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(stack.armyObj) : NULL;
  2488. const CGTownInstance *t = NULL;
  2489. if(stack.armyObj->ID == TOWNI_TYPE)
  2490. t = static_cast<const CGTownInstance *>(stack.armyObj);
  2491. else if(h)
  2492. { //hero speciality
  2493. BonusList lista = h->speciality.getBonuses(Selector::typeSybtype(Bonus::SPECIAL_UPGRADE, base->idNumber));
  2494. BOOST_FOREACH(const Bonus *it, lista)
  2495. {
  2496. ui16 nid = it->additionalInfo;
  2497. if (nid != base->idNumber) //in very specific case the upgrade is avaliable by default (?)
  2498. {
  2499. ret.newID.push_back(nid);
  2500. ret.cost.push_back(costDiff(VLC->creh->creatures[nid]->cost, base->cost));
  2501. }
  2502. }
  2503. t = h->visitedTown;
  2504. }
  2505. if(t)
  2506. {
  2507. BOOST_FOREACH(si32 bid, t->builtBuildings)
  2508. {
  2509. if( bid >= 37 && bid < 44 ) //upgraded creature dwelling
  2510. {
  2511. int nid = t->town->upgradedCreatures[bid-37]; //upgrade offered by that building
  2512. if(vstd::contains(base->upgrades, nid)) //possible upgrade
  2513. {
  2514. ret.newID.push_back(nid);
  2515. ret.cost.push_back(costDiff(VLC->creh->creatures[nid]->cost, base->cost));
  2516. }
  2517. }
  2518. }
  2519. }
  2520. //hero is visiting Hill Fort
  2521. if(h && map->getTile(h->visitablePos()).visitableObjects.front()->ID == 35)
  2522. {
  2523. static const int costModifiers[] = {0, 25, 50, 75, 100}; //we get cheaper upgrades depending on level
  2524. const int costModifier = costModifiers[std::min<int>(std::max((int)base->level - 1, 0), ARRAY_COUNT(costModifiers) - 1)];
  2525. BOOST_FOREACH(si32 nid, base->upgrades)
  2526. {
  2527. ret.newID.push_back(nid);
  2528. ret.cost.push_back(costDiff(VLC->creh->creatures[nid]->cost, base->cost, costModifier));
  2529. }
  2530. }
  2531. if(ret.newID.size())
  2532. ret.oldID = base->idNumber;
  2533. return ret;
  2534. }
  2535. int CGameState::getPlayerRelations( ui8 color1, ui8 color2 )
  2536. {
  2537. if ( color1 == color2 )
  2538. return 2;
  2539. const TeamState * ts = getPlayerTeam(color1);
  2540. if (ts && vstd::contains(ts->players, color2))
  2541. return 1;
  2542. return 0;
  2543. }
  2544. void CGameState::loadTownDInfos()
  2545. {
  2546. for(int i=0;i<F_NUMBER;i++)
  2547. {
  2548. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  2549. forts[i] = VLC->dobjinfo->castles[i];
  2550. map->defy.push_back(forts[i]);
  2551. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  2552. }
  2553. std::ifstream ifs(DATA_DIR "/config/townsDefs.txt");
  2554. int ccc;
  2555. ifs>>ccc;
  2556. for(int i=0; i < ccc*2; i++)
  2557. {
  2558. CGDefInfo *n;
  2559. if(i<ccc)
  2560. n = villages[i];
  2561. else
  2562. n = capitols[i%ccc];
  2563. ifs >> n->name;
  2564. map->defy.push_back(n);
  2565. }
  2566. }
  2567. void CGameState::getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing)
  2568. {
  2569. static int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  2570. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  2571. vec.clear();
  2572. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  2573. {
  2574. const int3 hlp = tile + dirs[i];
  2575. if(!map->isInTheMap(hlp))
  2576. continue;
  2577. const TerrainTile &hlpt = map->getTile(hlp);
  2578. //we cannot visit things from blocked tiles
  2579. if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  2580. {
  2581. continue;
  2582. }
  2583. if(srct.tertype == TerrainTile::water && limitCoastSailing && hlpt.tertype == TerrainTile::water && dirs[i].x && dirs[i].y) //diagonal move through water
  2584. {
  2585. int3 hlp1 = tile,
  2586. hlp2 = tile;
  2587. hlp1.x += dirs[i].x;
  2588. hlp2.y += dirs[i].y;
  2589. if(map->getTile(hlp1).tertype != TerrainTile::water || map->getTile(hlp2).tertype != TerrainTile::water)
  2590. continue;
  2591. }
  2592. if((indeterminate(onLand) || onLand == (hlpt.tertype!=TerrainTile::water) )
  2593. && hlpt.tertype != TerrainTile::rock)
  2594. {
  2595. vec.push_back(hlp);
  2596. }
  2597. }
  2598. }
  2599. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  2600. {
  2601. if(src == dest) //same tile
  2602. return 0;
  2603. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  2604. &d = map->terrain[dest.x][dest.y][dest.z];
  2605. //get basic cost
  2606. int ret = h->getTileCost(d,s);
  2607. if(d.blocked && h->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  2608. {
  2609. bool freeFlying = h->getBonusesCount(Selector::typeSybtype(Bonus::FLYING_MOVEMENT, 1)) > 0;
  2610. if(!freeFlying)
  2611. {
  2612. ret *= 1.4f; //40% penalty for movement over blocked tile
  2613. }
  2614. }
  2615. else if (d.tertype == TerrainTile::water)
  2616. {
  2617. if(h->boat && s.siodmyTajemniczyBajt & 128 && d.siodmyTajemniczyBajt & 128) //Favourable Winds
  2618. ret *= 0.666f;
  2619. else if (!h->boat && h->getBonusesCount(Selector::typeSybtype(Bonus::WATER_WALKING, 1)) > 0)
  2620. ret *= 1.4f; //40% penalty for water walking
  2621. }
  2622. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  2623. {
  2624. int old = ret;
  2625. ret *= 1.414213;
  2626. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  2627. if(ret > remainingMovePoints && remainingMovePoints >= old)
  2628. {
  2629. return remainingMovePoints;
  2630. }
  2631. }
  2632. int left = remainingMovePoints-ret;
  2633. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  2634. {
  2635. std::vector<int3> vec;
  2636. getNeighbours(d, dest, vec, s.tertype != TerrainTile::water, true);
  2637. for(size_t i=0; i < vec.size(); i++)
  2638. {
  2639. int fcost = getMovementCost(h,dest,vec[i],left,false);
  2640. if(fcost <= left)
  2641. {
  2642. return ret;
  2643. }
  2644. }
  2645. ret = remainingMovePoints;
  2646. }
  2647. return ret;
  2648. }
  2649. std::set<int> CGameState::getBuildingRequiments(const CGTownInstance *t, int ID)
  2650. {
  2651. std::set<int> used;
  2652. used.insert(ID);
  2653. std::set<int> reqs = VLC->townh->requirements[t->subID][ID];
  2654. while(true)
  2655. {
  2656. size_t noloop=0;
  2657. for(std::set<int>::iterator i=reqs.begin();i!=reqs.end();i++)
  2658. {
  2659. if(used.find(*i)==used.end()) //we haven't added requirements for this building
  2660. {
  2661. used.insert(*i);
  2662. for(
  2663. std::set<int>::iterator j=VLC->townh->requirements[t->subID][*i].begin();
  2664. j!=VLC->townh->requirements[t->subID][*i].end();
  2665. j++)
  2666. {
  2667. reqs.insert(*j);//creating full list of requirements
  2668. }
  2669. }
  2670. else
  2671. {
  2672. noloop++;
  2673. }
  2674. }
  2675. if(noloop==reqs.size())
  2676. break;
  2677. }
  2678. return reqs;
  2679. }
  2680. int CGameState::canBuildStructure( const CGTownInstance *t, int ID )
  2681. {
  2682. int ret = 7; //allowed by default
  2683. if(t->builded >= MAX_BUILDING_PER_TURN)
  2684. ret = 5; //building limit
  2685. //checking resources
  2686. CBuilding * pom = VLC->buildh->buildings[t->subID][ID];
  2687. if(!pom)
  2688. return 8;
  2689. // if(pom->Name().size()==0||pom->resources.size()==0)
  2690. // return 2;//TODO: why does this happen?
  2691. for(int res=0;res<pom->resources.size();res++) //TODO: support custom amount of resources
  2692. {
  2693. if(pom->resources[res] > getPlayer(t->tempOwner)->resources[res])
  2694. ret = 6; //lack of res
  2695. }
  2696. //checking for requirements
  2697. std::set<int> reqs = getBuildingRequiments(t, ID);//getting all requiments
  2698. for( std::set<int>::iterator ri = reqs.begin(); ri != reqs.end(); ri++ )
  2699. {
  2700. if(t->builtBuildings.find(*ri)==t->builtBuildings.end())
  2701. ret = 8; //lack of requirements - cannot build
  2702. }
  2703. //can we build it?
  2704. if(t->forbiddenBuildings.find(ID)!=t->forbiddenBuildings.end())
  2705. ret = 2; //forbidden
  2706. if(ID == 13) //capitol
  2707. {
  2708. for(unsigned int in = 0; in < map->towns.size(); in++)
  2709. {
  2710. if(map->towns[in]->tempOwner==t->tempOwner && vstd::contains(map->towns[in]->builtBuildings,13))
  2711. {
  2712. ret = 0; //no more than one capitol
  2713. break;
  2714. }
  2715. }
  2716. }
  2717. else if(ID == 6) //shipyard
  2718. {
  2719. int3 t1(t->pos + int3(-1,3,0)),
  2720. t2(t->pos + int3(-3,3,0));
  2721. if(map->isInTheMap(t1) && map->getTile(t1).tertype != TerrainTile::water
  2722. && (map->isInTheMap(t2) && map->getTile(t2).tertype != TerrainTile::water))
  2723. ret = 1; //lack of water
  2724. }
  2725. if(t->builtBuildings.find(ID)!=t->builtBuildings.end()) //already built
  2726. ret = 4;
  2727. return ret;
  2728. }
  2729. void CGameState::apply(CPack *pack)
  2730. {
  2731. ui16 typ = typeList.getTypeID(pack);
  2732. applierGs->apps[typ]->applyOnGS(this,pack);
  2733. }
  2734. TeamState *CGameState::getTeam(ui8 teamID)
  2735. {
  2736. if(vstd::contains(teams,teamID))
  2737. {
  2738. return &teams[teamID];
  2739. }
  2740. else
  2741. {
  2742. tlog2 << "Warning: Cannot find info for team " << int(teamID) << std::endl;
  2743. return NULL;
  2744. }
  2745. }
  2746. TeamState *CGameState::getPlayerTeam(ui8 color)
  2747. {
  2748. PlayerState * ps = getPlayer(color);
  2749. if (ps)
  2750. return getTeam(ps->team);
  2751. return NULL;
  2752. }
  2753. PlayerState * CGameState::getPlayer( ui8 color, bool verbose )
  2754. {
  2755. if(vstd::contains(players,color))
  2756. {
  2757. return &players[color];
  2758. }
  2759. else
  2760. {
  2761. if(verbose)
  2762. tlog2 << "Warning: Cannot find info for player " << int(color) << std::endl;
  2763. return NULL;
  2764. }
  2765. }
  2766. const PlayerState * CGameState::getPlayer( ui8 color, bool verbose ) const
  2767. {
  2768. return (const_cast<CGameState *>(this))->getPlayer(color, verbose);
  2769. }
  2770. const TeamState * CGameState::getTeam( ui8 teamID ) const
  2771. {
  2772. return (const_cast<CGameState *>(this))->getTeam(teamID);
  2773. }
  2774. const TeamState * CGameState::getPlayerTeam( ui8 teamID ) const
  2775. {
  2776. return (const_cast<CGameState *>(this))->getPlayerTeam(teamID);
  2777. }
  2778. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  2779. {
  2780. if(!map->isInTheMap(src) || !map->isInTheMap(dest)) //check input
  2781. return false;
  2782. int3 hpos = hero->getPosition(false);
  2783. bool flying = false; //hero is under flying effect TODO
  2784. bool waterWalking = false; //hero is on land and can walk on water TODO
  2785. bool onLand = map->getTile(hpos).tertype != TerrainTile::water;
  2786. // tribool blockLandSea; //true - blocks sea, false - blocks land, indeterminate - allows all
  2787. //
  2788. // if (!hero->canWalkOnSea())
  2789. // blockLandSea = (map->getTile(hpos).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  2790. // else
  2791. // blockLandSea = boost::logic::indeterminate;
  2792. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayerTeam(hero->tempOwner)->fogOfWarMap;
  2793. //graph initialization
  2794. std::vector< std::vector<CPathNode> > graph;
  2795. graph.resize(map->width);
  2796. for(size_t i=0; i<graph.size(); ++i)
  2797. {
  2798. graph[i].resize(map->height);
  2799. for(size_t j=0; j<graph[i].size(); ++j)
  2800. {
  2801. const TerrainTile *tinfo = &map->terrain[i][j][src.z];
  2802. CPathNode &node = graph[i][j];
  2803. node.accessible = !tinfo->blocked;
  2804. node.dist = -1;
  2805. node.theNodeBefore = NULL;
  2806. node.visited = false;
  2807. node.coord.x = i;
  2808. node.coord.y = j;
  2809. node.coord.z = dest.z;
  2810. if(!tinfo->entrableTerrain(onLand, flying || waterWalking)
  2811. || !FoW[i][j][src.z] //tile is covered by the FoW
  2812. )
  2813. {
  2814. node.accessible = false;
  2815. }
  2816. }
  2817. }
  2818. //Special rules for the destination tile
  2819. {
  2820. const TerrainTile *t = &map->terrain[dest.x][dest.y][dest.z];
  2821. CPathNode &d = graph[dest.x][dest.y];
  2822. //tile may be blocked by blockvis / normal vis obj but it still must be accessible
  2823. if(t->visitable)
  2824. {
  2825. d.accessible = true; //for allowing visiting objects
  2826. }
  2827. if(onLand && t->tertype == TerrainTile::water) //hero can walk only on land and dst lays on the water
  2828. {
  2829. size_t i = 0;
  2830. for(; i < t->visitableObjects.size(); i++)
  2831. if(t->visitableObjects[i]->ID == 8 || t->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  2832. break;
  2833. d.accessible = (i < t->visitableObjects.size()); //dest is accessible only if there is boat/hero
  2834. }
  2835. else if(!onLand && t->tertype != TerrainTile::water) //hero is moving by water
  2836. {
  2837. d.accessible = (t->siodmyTajemniczyBajt & 64) && !t->blocked; //tile is accessible if it's coastal and not blocked
  2838. }
  2839. }
  2840. //graph initialized
  2841. //initial tile - set cost on 0 and add to the queue
  2842. graph[src.x][src.y].dist = 0;
  2843. std::queue<CPathNode> mq;
  2844. mq.push(graph[src.x][src.y]);
  2845. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  2846. std::vector<int3> neighbours;
  2847. neighbours.reserve(8);
  2848. while(!mq.empty())
  2849. {
  2850. CPathNode &cp = graph[mq.front().coord.x][mq.front().coord.y];
  2851. mq.pop();
  2852. if (cp.coord == dest) //it's destination tile
  2853. {
  2854. if (cp.dist < curDist) //that path is better than previous one
  2855. curDist = cp.dist;
  2856. continue;
  2857. }
  2858. else
  2859. {
  2860. if (cp.dist > curDist) //it's not dest and current length is greater than cost of already found path
  2861. continue;
  2862. }
  2863. //add accessible neighbouring nodes to the queue
  2864. getNeighbours(map->getTile(cp.coord), cp.coord, neighbours, boost::logic::indeterminate, true);
  2865. for(unsigned int i=0; i < neighbours.size(); i++)
  2866. {
  2867. CPathNode & dp = graph[neighbours[i].x][neighbours[i].y];
  2868. if(dp.accessible)
  2869. {
  2870. int cost = getMovementCost(hero,cp.coord,dp.coord,hero->movement - cp.dist);
  2871. if((dp.dist==-1 || (dp.dist > cp.dist + cost)) && dp.accessible && checkForVisitableDir(cp.coord, dp.coord) && checkForVisitableDir(dp.coord, cp.coord))
  2872. {
  2873. dp.dist = cp.dist + cost;
  2874. dp.theNodeBefore = &cp;
  2875. mq.push(dp);
  2876. }
  2877. }
  2878. }
  2879. }
  2880. CPathNode *curNode = &graph[dest.x][dest.y];
  2881. if(!curNode->theNodeBefore) //destination is not accessible
  2882. return false;
  2883. //fill ret with found path
  2884. ret.nodes.clear();
  2885. while(curNode->coord != graph[src.x][src.y].coord)
  2886. {
  2887. ret.nodes.push_back(*curNode);
  2888. curNode = curNode->theNodeBefore;
  2889. }
  2890. ret.nodes.push_back(graph[src.x][src.y]);
  2891. return true;
  2892. }
  2893. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  2894. {
  2895. assert(hero);
  2896. boost::shared_lock<boost::shared_mutex> lock(*mx);
  2897. if(src.x < 0)
  2898. src = hero->getPosition(false);
  2899. if(movement < 0)
  2900. movement = hero->movement;
  2901. out.hero = hero;
  2902. out.hpos = src;
  2903. if(!map->isInTheMap(src)/* || !map->isInTheMap(dest)*/) //check input
  2904. {
  2905. tlog1 << "CGameState::calculatePaths: Hero outside the map? How dare you...\n";
  2906. return;
  2907. }
  2908. tribool onLand; //true - blocks sea, false - blocks land, indeterminate - allows all
  2909. if (!hero->canWalkOnSea())
  2910. onLand = (map->getTile(src).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  2911. else
  2912. onLand = boost::logic::indeterminate;
  2913. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayerTeam(hero->tempOwner)->fogOfWarMap;
  2914. bool flying = hero->hasBonusOfType(Bonus::FLYING_MOVEMENT);
  2915. bool waterWalk = hero->hasBonusOfType(Bonus::WATER_WALKING);
  2916. //graph initialization
  2917. CGPathNode ***graph = out.nodes;
  2918. for(size_t i=0; i < out.sizes.x; ++i)
  2919. {
  2920. for(size_t j=0; j < out.sizes.y; ++j)
  2921. {
  2922. for(size_t k=0; k < out.sizes.z; ++k)
  2923. {
  2924. const TerrainTile *tinfo = &map->terrain[i][j][k];
  2925. CGPathNode &node = graph[i][j][k];
  2926. node.accessible = (tinfo->blocked ? CGPathNode::FLYABLE : CGPathNode::ACCESSIBLE);
  2927. if(!flying && node.accessible == CGPathNode::FLYABLE)
  2928. {
  2929. node.accessible = CGPathNode::BLOCKED;
  2930. }
  2931. node.turns = 0xff;
  2932. node.moveRemains = 0;
  2933. node.coord.x = i;
  2934. node.coord.y = j;
  2935. node.coord.z = k;
  2936. node.land = tinfo->tertype != TerrainTile::water;
  2937. node.theNodeBefore = NULL;
  2938. bool leaveAsBlocked = false;
  2939. if((onLand || indeterminate(onLand)) && !node.land)//it's sea and we cannot walk on sea
  2940. {
  2941. if (waterWalk || flying)
  2942. {
  2943. node.accessible = CGPathNode::FLYABLE;
  2944. }
  2945. else
  2946. {
  2947. node.accessible = CGPathNode::BLOCKED;
  2948. leaveAsBlocked = true;
  2949. }
  2950. }
  2951. if ( tinfo->tertype == TerrainTile::rock//it's rock
  2952. || (!onLand && node.land) //it's land and we cannot walk on land (complementary condition is handled above)
  2953. || !FoW[i][j][k] //tile is covered by the FoW
  2954. || leaveAsBlocked
  2955. )
  2956. {
  2957. node.accessible = CGPathNode::BLOCKED;
  2958. }
  2959. else if(tinfo->visitable)
  2960. {
  2961. //hero is protected in Sanctuary
  2962. if(tinfo->visitableObjects.front()->ID == 80 && tinfo->visitableObjects.back()->ID == HEROI_TYPE && tinfo->visitableObjects.back()->tempOwner != hero->tempOwner)
  2963. node.accessible = CGPathNode::BLOCKED;
  2964. else
  2965. {
  2966. for(size_t ii = 0; ii < tinfo->visitableObjects.size(); ii++)
  2967. {
  2968. const CGObjectInstance * const obj = tinfo->visitableObjects[ii];
  2969. if(obj->getPassableness() & 1<<hero->tempOwner) //special object instance specific passableness flag - overwrites other accessibility flags
  2970. {
  2971. node.accessible = CGPathNode::ACCESSIBLE;
  2972. }
  2973. else if(obj->blockVisit)
  2974. {
  2975. node.accessible = CGPathNode::BLOCKVIS;
  2976. break;
  2977. }
  2978. else if(obj->ID != EVENTI_TYPE) //pathfinder should ignore placed events
  2979. {
  2980. node.accessible = CGPathNode::VISITABLE;
  2981. }
  2982. }
  2983. }
  2984. }
  2985. else if (map->isInTheMap(guardingCreaturePosition(int3(i, j, k)))
  2986. && tinfo->blockingObjects.size() == 0)
  2987. {
  2988. // Monster close by; blocked visit for battle.
  2989. node.accessible = CGPathNode::BLOCKVIS;
  2990. }
  2991. if(onLand && !node.land) //hero can walk only on land and tile lays on the water
  2992. {
  2993. size_t i = 0;
  2994. for(; i < tinfo->visitableObjects.size(); i++)
  2995. if(tinfo->visitableObjects[i]->ID == 8 || tinfo->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  2996. break;
  2997. if(i < tinfo->visitableObjects.size())
  2998. node.accessible = CGPathNode::BLOCKVIS; //dest is accessible only if there is boat/hero
  2999. }
  3000. else if(!onLand && tinfo->tertype != TerrainTile::water) //hero is moving by water
  3001. {
  3002. if((tinfo->siodmyTajemniczyBajt & 64) && !tinfo->blocked)
  3003. node.accessible = CGPathNode::VISITABLE; //tile is accessible if it's coastal and not blocked
  3004. }
  3005. }
  3006. }
  3007. }
  3008. //graph initialized
  3009. //initial tile - set cost on 0 and add to the queue
  3010. graph[src.x][src.y][src.z].turns = 0;
  3011. graph[src.x][src.y][src.z].moveRemains = movement;
  3012. std::queue<CGPathNode*> mq;
  3013. mq.push(&graph[src.x][src.y][src.z]);
  3014. //ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  3015. std::vector<int3> neighbours;
  3016. neighbours.reserve(8);
  3017. while(!mq.empty())
  3018. {
  3019. CGPathNode *cp = mq.front();
  3020. mq.pop();
  3021. const int3 guardPosition = guardingCreaturePosition(cp->coord);
  3022. const bool guardedPosition = (guardPosition != int3(-1, -1, -1) && cp->coord != src);
  3023. const TerrainTile &ct = map->getTile(cp->coord);
  3024. int movement = cp->moveRemains, turn = cp->turns;
  3025. if(!movement)
  3026. {
  3027. movement = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  3028. turn++;
  3029. }
  3030. //add accessible neighbouring nodes to the queue
  3031. getNeighbours(ct, cp->coord, neighbours, boost::logic::indeterminate, !onLand);
  3032. for(unsigned int i=0; i < neighbours.size(); i++)
  3033. {
  3034. int moveAtNextTile = movement;
  3035. int turnAtNextTile = turn;
  3036. const int3 &n = neighbours[i]; //current neighbor
  3037. CGPathNode & dp = graph[n.x][n.y][n.z];
  3038. if( !checkForVisitableDir(cp->coord, dp.coord)
  3039. || !checkForVisitableDir(dp.coord, cp->coord)
  3040. || dp.accessible == CGPathNode::BLOCKED )
  3041. {
  3042. continue;
  3043. }
  3044. int cost = getMovementCost(hero, cp->coord, dp.coord, movement);
  3045. int remains = movement - cost;
  3046. if(remains < 0)
  3047. {
  3048. //occurs rarely, when hero with low movepoints tries to go leave the road
  3049. turnAtNextTile++;
  3050. moveAtNextTile = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  3051. cost = getMovementCost(hero, cp->coord, dp.coord, moveAtNextTile); //cost must be updated, movement points changed :(
  3052. remains = moveAtNextTile - cost;
  3053. }
  3054. const bool neighborIsGuard = guardingCreaturePosition(cp->coord) == dp.coord;
  3055. if((dp.turns==0xff //we haven't been here before
  3056. || dp.turns > turnAtNextTile
  3057. || (dp.turns >= turnAtNextTile && dp.moveRemains < remains)) //this route is faster
  3058. && (!guardedPosition || neighborIsGuard)) // Can step into tile of guard
  3059. {
  3060. assert(&dp != cp->theNodeBefore); //two tiles can't point to each other
  3061. dp.moveRemains = remains;
  3062. dp.turns = turnAtNextTile;
  3063. dp.theNodeBefore = cp;
  3064. const bool guardedNeighbor = guardingCreaturePosition(dp.coord) != int3(-1, -1, -1);
  3065. //const bool positionIsGuard = guardingCreaturePosition(cp->coord) == cp->coord; //can this be true? hero never passes from monster tile...
  3066. if (dp.accessible == CGPathNode::ACCESSIBLE || dp.accessible == CGPathNode::FLYABLE
  3067. || (guardedNeighbor && !guardedPosition)) // Can step into a hostile tile once.
  3068. {
  3069. mq.push(&dp);
  3070. }
  3071. }
  3072. } //neighbours loop
  3073. } //queue loop
  3074. }
  3075. /**
  3076. * Tells if the tile is guarded by a monster as well as the position
  3077. * of the monster that will attack on it.
  3078. *
  3079. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  3080. * the monster guarding the tile.
  3081. */
  3082. int3 CGameState::guardingCreaturePosition (int3 pos) const
  3083. {
  3084. const int3 originalPos = pos;
  3085. // Give monster at position priority.
  3086. if (!map->isInTheMap(pos))
  3087. return int3(-1, -1, -1);
  3088. const TerrainTile &posTile = map->terrain[pos.x][pos.y][pos.z];
  3089. if (posTile.visitable)
  3090. {
  3091. BOOST_FOREACH (CGObjectInstance* obj, posTile.visitableObjects)
  3092. {
  3093. if(obj->blockVisit)
  3094. {
  3095. if (obj->ID == 54) // Monster
  3096. return pos;
  3097. else
  3098. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  3099. }
  3100. }
  3101. }
  3102. // See if there are any monsters adjacent.
  3103. pos -= int3(1, 1, 0); // Start with top left.
  3104. for (int dx = 0; dx < 3; dx++)
  3105. {
  3106. for (int dy = 0; dy < 3; dy++)
  3107. {
  3108. if (map->isInTheMap(pos))
  3109. {
  3110. TerrainTile &tile = map->terrain[pos.x][pos.y][pos.z];
  3111. if (tile.visitable && (tile.tertype == TerrainTile::water) == (posTile.tertype == TerrainTile::water))
  3112. {
  3113. BOOST_FOREACH (CGObjectInstance* obj, tile.visitableObjects)
  3114. {
  3115. if (obj->ID == 54 && checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  3116. {
  3117. return pos;
  3118. }
  3119. }
  3120. }
  3121. }
  3122. pos.y++;
  3123. }
  3124. pos.y -= 3;
  3125. pos.x++;
  3126. }
  3127. return int3(-1, -1, -1);
  3128. }
  3129. bool CGameState::isVisible(int3 pos, int player)
  3130. {
  3131. if(player == 255) //neutral player
  3132. return false;
  3133. return getPlayerTeam(player)->fogOfWarMap[pos.x][pos.y][pos.z];
  3134. }
  3135. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  3136. {
  3137. if(player == 255) //neutral player
  3138. return false;
  3139. //object is visible when at least one blocked tile is visible
  3140. for(int fx=0; fx<8; ++fx)
  3141. {
  3142. for(int fy=0; fy<6; ++fy)
  3143. {
  3144. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  3145. if(map->isInTheMap(pos)
  3146. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  3147. && isVisible(pos, player) )
  3148. return true;
  3149. }
  3150. }
  3151. return false;
  3152. }
  3153. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  3154. {
  3155. const TerrainTile * pom = &map->getTile(dst);
  3156. return checkForVisitableDir(src, pom, dst);
  3157. }
  3158. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  3159. {
  3160. for(unsigned int b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  3161. {
  3162. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  3163. continue;
  3164. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  3165. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  3166. {
  3167. return false;
  3168. }
  3169. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  3170. {
  3171. return false;
  3172. }
  3173. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  3174. {
  3175. return false;
  3176. }
  3177. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  3178. {
  3179. return false;
  3180. }
  3181. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  3182. {
  3183. return false;
  3184. }
  3185. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  3186. {
  3187. return false;
  3188. }
  3189. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  3190. {
  3191. return false;
  3192. }
  3193. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  3194. {
  3195. return false;
  3196. }
  3197. }
  3198. return true;
  3199. }
  3200. std::pair<ui32, ui32> BattleInfo::calculateDmgRange( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky )
  3201. {
  3202. float additiveBonus=1.0f, multBonus=1.0f,
  3203. minDmg = attacker->getMinDamage() * attacker->count,
  3204. maxDmg = attacker->getMaxDamage() * attacker->count;
  3205. if(attacker->getCreature()->idNumber == 149) //arrow turret
  3206. {
  3207. switch(attacker->position)
  3208. {
  3209. case -2: //keep
  3210. minDmg = 15;
  3211. maxDmg = 15;
  3212. break;
  3213. case -3: case -4: //turrets
  3214. minDmg = 7.5f;
  3215. maxDmg = 7.5f;
  3216. break;
  3217. }
  3218. }
  3219. if(attacker->hasBonusOfType(Bonus::SIEGE_WEAPON) && attacker->getCreature()->idNumber != 149) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  3220. { //minDmg and maxDmg are multiplied by hero attack + 1
  3221. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  3222. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  3223. }
  3224. int attackDefenceDifference = 0;
  3225. if(attacker->hasBonusOfType(Bonus::GENERAL_ATTACK_REDUCTION))
  3226. {
  3227. float multAttackReduction = attacker->valOfBonuses(Bonus::GENERAL_ATTACK_REDUCTION, -1024) / 100.0f;
  3228. attackDefenceDifference = attacker->Attack() * multAttackReduction;
  3229. }
  3230. else
  3231. {
  3232. attackDefenceDifference = attacker->Attack();
  3233. }
  3234. if(attacker->hasBonusOfType(Bonus::ENEMY_DEFENCE_REDUCTION))
  3235. {
  3236. float multDefenceReduction = (100.0f - attacker->valOfBonuses(Bonus::ENEMY_DEFENCE_REDUCTION, -1024)) / 100.0f;
  3237. attackDefenceDifference -= defender->Defense() * multDefenceReduction;
  3238. }
  3239. else
  3240. {
  3241. attackDefenceDifference -= defender->Defense();
  3242. }
  3243. //calculating total attack/defense skills modifier
  3244. if(shooting) //precision handling (etc.)
  3245. attackDefenceDifference += attacker->getBonuses(Selector::typeSybtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT)).totalValue();
  3246. else //bloodlust handling (etc.)
  3247. attackDefenceDifference += attacker->getBonuses(Selector::typeSybtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_MELEE_FIGHT)).totalValue();
  3248. if(attacker->getEffect(55)) //slayer handling
  3249. {
  3250. std::vector<int> affectedIds;
  3251. int spLevel = attacker->getEffect(55)->val;
  3252. for(int g = 0; g < VLC->creh->creatures.size(); ++g)
  3253. {
  3254. BOOST_FOREACH(const Bonus *b, VLC->creh->creatures[g]->bonuses)
  3255. {
  3256. if ( (b->type == Bonus::KING3 && spLevel >= 3) || //expert
  3257. (b->type == Bonus::KING2 && spLevel >= 2) || //adv +
  3258. (b->type == Bonus::KING1 && spLevel >= 0) ) //none or basic +
  3259. {
  3260. affectedIds.push_back(g);
  3261. break;
  3262. }
  3263. }
  3264. }
  3265. for(unsigned int g=0; g<affectedIds.size(); ++g)
  3266. {
  3267. if(defender->getCreature()->idNumber == affectedIds[g])
  3268. {
  3269. attackDefenceDifference += VLC->spellh->spells[55]->powers[attacker->getEffect(55)->val];
  3270. break;
  3271. }
  3272. }
  3273. }
  3274. //bonus from attack/defense skills
  3275. if(attackDefenceDifference < 0) //decreasing dmg
  3276. {
  3277. float dec = 0.025f * (-attackDefenceDifference);
  3278. if(dec > 0.7f)
  3279. {
  3280. multBonus *= 0.3f; //1.0 - 0.7
  3281. }
  3282. else
  3283. {
  3284. multBonus *= 1.0f - dec;
  3285. }
  3286. }
  3287. else //increasing dmg
  3288. {
  3289. float inc = 0.05f * attackDefenceDifference;
  3290. if(inc > 4.0f)
  3291. {
  3292. additiveBonus += 4.0f;
  3293. }
  3294. else
  3295. {
  3296. additiveBonus += inc;
  3297. }
  3298. }
  3299. //applying jousting bonus
  3300. if( attacker->hasBonusOfType(Bonus::JOUSTING) && !defender->hasBonusOfType(Bonus::CHARGE_IMMUNITY) )
  3301. additiveBonus += charge * 0.05f;
  3302. //handling secondary abilities and artifacts giving premies to them
  3303. if(attackerHero)
  3304. {
  3305. if(shooting)
  3306. {
  3307. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 1) / 100.0f;
  3308. }
  3309. else
  3310. {
  3311. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 22) / 100.0f;
  3312. }
  3313. }
  3314. if(defendingHero)
  3315. {
  3316. multBonus *= (std::max(0, 100-defendingHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 23))) / 100.0f;
  3317. }
  3318. //handling hate effect
  3319. if( attacker->hasBonusOfType(Bonus::HATE, defender->getCreature()->idNumber) )
  3320. additiveBonus += 0.5f;
  3321. //luck bonus
  3322. if (lucky)
  3323. {
  3324. additiveBonus += 1.0f;
  3325. }
  3326. //handling spell effects
  3327. if(!shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  3328. {
  3329. multBonus *= float(defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0f;
  3330. }
  3331. else if(shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  3332. {
  3333. multBonus *= float(defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0f;
  3334. }
  3335. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  3336. {
  3337. multBonus *= 0.8f * float(VLC->spellh->spells[42]->powers[attacker->getEffect(42)->val]); //the second factor is 1 or 0
  3338. }
  3339. class HLP
  3340. {
  3341. public:
  3342. static bool hasAdvancedAirShield(const CStack * stack)
  3343. {
  3344. BOOST_FOREACH(const Bonus *it, stack->bonuses)
  3345. {
  3346. if (it->source == Bonus::SPELL_EFFECT && it->id == 28 && it->val >= 2)
  3347. {
  3348. return true;
  3349. }
  3350. }
  3351. return false;
  3352. }
  3353. };
  3354. //wall / distance penalty + advanced air shield
  3355. if (shooting && !NBonus::hasOfType(attackerHero, Bonus::NO_SHOTING_PENALTY) && (
  3356. hasDistancePenalty(attacker->ID, defender->position) || hasWallPenalty(attacker->ID, defender->position) ||
  3357. HLP::hasAdvancedAirShield(defender) )
  3358. )
  3359. {
  3360. multBonus *= 0.5;
  3361. }
  3362. if (!shooting && attacker->hasBonusOfType(Bonus::SHOOTER) && !attacker->hasBonusOfType(Bonus::NO_MELEE_PENALTY))
  3363. {
  3364. multBonus *= 0.5;
  3365. }
  3366. minDmg *= additiveBonus * multBonus;
  3367. maxDmg *= additiveBonus * multBonus;
  3368. std::pair<ui32, ui32> returnedVal;
  3369. if(attacker->getEffect(42)) //curse handling (rest)
  3370. {
  3371. minDmg -= VLC->spellh->spells[42]->powers[attacker->getEffect(42)->val];
  3372. returnedVal = std::make_pair(int(minDmg), int(minDmg));
  3373. }
  3374. else if(attacker->getEffect(41)) //bless handling
  3375. {
  3376. maxDmg += VLC->spellh->spells[41]->powers[attacker->getEffect(41)->val];
  3377. returnedVal = std::make_pair(int(maxDmg), int(maxDmg));
  3378. }
  3379. else
  3380. {
  3381. returnedVal = std::make_pair(int(minDmg), int(maxDmg));
  3382. }
  3383. //damage cannot be less than 1
  3384. amax(returnedVal.first, 1);
  3385. amax(returnedVal.second, 1);
  3386. return returnedVal;
  3387. }
  3388. ui32 BattleInfo::calculateDmg( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky )
  3389. {
  3390. std::pair<ui32, ui32> range = calculateDmgRange(attacker, defender, attackerHero, defendingHero, shooting, charge, lucky);
  3391. if(range.first != range.second)
  3392. {
  3393. int valuesToAverage[10];
  3394. int howManyToAv = std::min<ui32>(10, attacker->count);
  3395. for (int g=0; g<howManyToAv; ++g)
  3396. {
  3397. valuesToAverage[g] = range.first + rand() % (range.second - range.first + 1);
  3398. }
  3399. return std::accumulate(valuesToAverage, valuesToAverage + howManyToAv, 0) / howManyToAv;
  3400. }
  3401. else
  3402. return range.first;
  3403. }
  3404. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  3405. {
  3406. for(unsigned int i=0; i<stacks.size();i++)//setting casualties
  3407. {
  3408. const CStack * const st = stacks[i];
  3409. si32 killed = (st->alive() ? st->baseAmount - st->count : st->baseAmount);
  3410. amax(killed, 0);
  3411. if(killed)
  3412. casualties[!st->attackerOwned][st->getCreature()->idNumber] += killed;
  3413. }
  3414. }
  3415. si8 CGameState::battleMaxSpellLevel()
  3416. {
  3417. if(!curB) //there is not battle
  3418. {
  3419. tlog1 << "si8 CGameState::maxSpellLevel() call when there is no battle!" << std::endl;
  3420. throw "si8 CGameState::maxSpellLevel() call when there is no battle!";
  3421. }
  3422. si8 levelLimit = SPELL_LEVELS;
  3423. const CGHeroInstance *h1 = curB->heroes[0];
  3424. if(h1)
  3425. {
  3426. BOOST_FOREACH(const Bonus *i, h1->bonuses)
  3427. if(i->type == Bonus::BLOCK_SPELLS_ABOVE_LEVEL)
  3428. amin(levelLimit, i->val);
  3429. }
  3430. const CGHeroInstance *h2 = curB->heroes[1];
  3431. if(h2)
  3432. {
  3433. BOOST_FOREACH(const Bonus *i, h2->bonuses)
  3434. if(i->type == Bonus::BLOCK_SPELLS_ABOVE_LEVEL)
  3435. amin(levelLimit, i->val);
  3436. }
  3437. return levelLimit;
  3438. }
  3439. std::set<CStack*> BattleInfo::getAttackedCreatures( const CSpell * s, int skillLevel, ui8 attackerOwner, int destinationTile )
  3440. {
  3441. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, skillLevel);
  3442. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
  3443. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  3444. if(s->id == 24 || s->id == 25 || s->id == 26) //death ripple, destroy undead and Armageddon
  3445. {
  3446. for(int it=0; it<stacks.size(); ++it)
  3447. {
  3448. if((s->id == 24 && !stacks[it]->getCreature()->isUndead()) //death ripple
  3449. || (s->id == 25 && stacks[it]->getCreature()->isUndead()) //destroy undead
  3450. || (s->id == 26) //Armageddon
  3451. )
  3452. {
  3453. if(stacks[it]->alive())
  3454. attackedCres.insert(stacks[it]);
  3455. }
  3456. }
  3457. }
  3458. else if (s->range[skillLevel].size() > 1) //custom many-hex range
  3459. {
  3460. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  3461. {
  3462. CStack * st = getStackT(*it, onlyAlive);
  3463. if(st)
  3464. attackedCres.insert(st);
  3465. }
  3466. }
  3467. else if(VLC->spellh->spells[s->id]->attributes.find("CREATURE_TARGET_1") != std::string::npos
  3468. || VLC->spellh->spells[s->id]->attributes.find("CREATURE_TARGET_2") != std::string::npos) //spell to be cast on a specific creature but massive on expert
  3469. {
  3470. if(skillLevel < 3) /*not expert */
  3471. {
  3472. CStack * st = getStackT(destinationTile, onlyAlive);
  3473. if(st)
  3474. attackedCres.insert(st);
  3475. }
  3476. else
  3477. {
  3478. for(int it=0; it<stacks.size(); ++it)
  3479. {
  3480. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  3481. if((VLC->spellh->spells[s->id]->positiveness >= 0 && stacks[it]->owner == attackerOwner)
  3482. ||(VLC->spellh->spells[s->id]->positiveness <= 0 && stacks[it]->owner != attackerOwner )
  3483. )
  3484. {
  3485. if(!onlyAlive || stacks[it]->alive())
  3486. attackedCres.insert(stacks[it]);
  3487. }
  3488. }
  3489. } //if(caster->getSpellSchoolLevel(s) < 3)
  3490. }
  3491. else if(VLC->spellh->spells[s->id]->attributes.find("CREATURE_TARGET") != std::string::npos) //spell to be cast on one specific creature
  3492. {
  3493. CStack * st = getStackT(destinationTile, onlyAlive);
  3494. if(st)
  3495. attackedCres.insert(st);
  3496. }
  3497. else //custom range from attackedHexes
  3498. {
  3499. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  3500. {
  3501. CStack * st = getStackT(*it, onlyAlive);
  3502. if(st)
  3503. attackedCres.insert(st);
  3504. }
  3505. }
  3506. return attackedCres;
  3507. }
  3508. int BattleInfo::calculateSpellDuration( const CSpell * spell, const CGHeroInstance * caster, int usedSpellPower )
  3509. {
  3510. if(!caster) //TODO: something better
  3511. return std::max(5, usedSpellPower);
  3512. switch(spell->id)
  3513. {
  3514. case 56: //frenzy
  3515. return 1;
  3516. default: //other spells
  3517. return caster->getPrimSkillLevel(2) + caster->valOfBonuses(Bonus::SPELL_DURATION);
  3518. }
  3519. }
  3520. CStack * BattleInfo::generateNewStack(const CStackInstance &base, int stackID, bool attackerOwned, int slot, int position) const
  3521. {
  3522. int owner = attackerOwned ? side1 : side2;
  3523. assert(owner >= PLAYER_LIMIT || base.armyObj && base.armyObj->tempOwner == owner);
  3524. CStack * ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  3525. ret->position = position;
  3526. return ret;
  3527. }
  3528. CStack * BattleInfo::generateNewStack(const CStackBasicDescriptor &base, int stackID, bool attackerOwned, int slot, int position) const
  3529. {
  3530. int owner = attackerOwned ? side1 : side2;
  3531. CStack * ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  3532. ret->position = position;
  3533. return ret;
  3534. }
  3535. ui32 BattleInfo::getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  3536. {
  3537. ui32 ret = caster->getSpellCost(sp);
  3538. //checking for friendly stacks reducing cost of the spell and
  3539. //enemy stacks increasing it
  3540. si32 manaReduction = 0;
  3541. si32 manaIncrease = 0;
  3542. for(int g=0; g<stacks.size(); ++g)
  3543. {
  3544. if( stacks[g]->owner == caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY) )
  3545. {
  3546. amin(manaReduction, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  3547. }
  3548. if( stacks[g]->owner != caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY) )
  3549. {
  3550. amax(manaIncrease, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  3551. }
  3552. }
  3553. return ret + manaReduction + manaIncrease;
  3554. }
  3555. int BattleInfo::hexToWallPart(int hex) const
  3556. {
  3557. if(siege == 0) //there is no battle!
  3558. return -1;
  3559. static const std::pair<int, int> attackable[] = //potentially attackable parts of wall
  3560. {std::make_pair(50, 0), std::make_pair(183, 1), std::make_pair(182, 2), std::make_pair(130, 3),
  3561. std::make_pair(62, 4), std::make_pair(29, 5), std::make_pair(12, 6), std::make_pair(95, 7), std::make_pair(96, 7)};
  3562. for(int g = 0; g < ARRAY_COUNT(attackable); ++g)
  3563. {
  3564. if(attackable[g].first == hex)
  3565. return attackable[g].second;
  3566. }
  3567. return -1; //not found!
  3568. }
  3569. int BattleInfo::lineToWallHex( int line ) const
  3570. {
  3571. static const int lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
  3572. return lineToHex[line];
  3573. }
  3574. std::pair<const CStack *, int> BattleInfo::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  3575. {
  3576. bool ac[BFIELD_SIZE];
  3577. std::set<int> occupyable;
  3578. getAccessibilityMap(ac, closest->doubleWide(), closest->attackerOwned, false, occupyable, closest->hasBonusOfType(Bonus::FLYING), closest->ID);
  3579. int predecessor[BFIELD_SIZE], dist[BFIELD_SIZE];
  3580. makeBFS(closest->position, ac, predecessor, dist, closest->doubleWide(), closest->attackerOwned, closest->hasBonusOfType(Bonus::FLYING), true);
  3581. std::vector< std::pair< std::pair<int, int>, const CStack *> > stackPairs; //pairs <<distance, hex>, stack>
  3582. for(int g=0; g<BFIELD_SIZE; ++g)
  3583. {
  3584. const CStack * atG = getStackT(g);
  3585. if(!atG || atG->ID == closest->ID) //if there is not stack or we are the closest one
  3586. continue;
  3587. if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  3588. {
  3589. if(predecessor[g] == -1) //TODO: is it really the best solution?
  3590. continue;
  3591. stackPairs.push_back( std::make_pair( std::make_pair(dist[predecessor[g]], g), atG) );
  3592. }
  3593. }
  3594. if(stackPairs.size() > 0)
  3595. {
  3596. std::vector< std::pair< std::pair<int, int>, const CStack *> > minimalPairs;
  3597. minimalPairs.push_back(stackPairs[0]);
  3598. for(int b=1; b<stackPairs.size(); ++b)
  3599. {
  3600. if(stackPairs[b].first.first < minimalPairs[0].first.first)
  3601. {
  3602. minimalPairs.clear();
  3603. minimalPairs.push_back(stackPairs[b]);
  3604. }
  3605. else if(stackPairs[b].first.first == minimalPairs[0].first.first)
  3606. {
  3607. minimalPairs.push_back(stackPairs[b]);
  3608. }
  3609. }
  3610. std::pair< std::pair<int, int>, const CStack *> minPair = minimalPairs[minimalPairs.size()/2];
  3611. return std::make_pair(minPair.second, predecessor[minPair.first.second]);
  3612. }
  3613. return std::make_pair<const CStack * , int>(NULL, -1);
  3614. }
  3615. ui32 BattleInfo::calculateSpellBonus(ui32 baseDamage, const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature) const
  3616. {
  3617. ui32 ret = baseDamage;
  3618. //applying sorcery secondary skill
  3619. if(caster)
  3620. {
  3621. ret *= (100.f + caster->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 25)) / 100.0f; //sorcery
  3622. ret *= (100.f + caster->valOfBonuses(Bonus::SPELL_DAMAGE) + caster->valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, sp->id)) / 100.0f;
  3623. if(sp->air)
  3624. ret *= (100.0f + caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY)) / 100.0f;
  3625. else if(sp->fire) //only one type of bonus for Magic Arrow
  3626. ret *= (100.0f + caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY)) / 100.0f;
  3627. else if(sp->water)
  3628. ret *= (100.0f + caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY)) / 100.0f;
  3629. else if(sp->earth)
  3630. ret *= (100.0f + caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY)) / 100.0f;
  3631. if (affectedCreature) //Hero specials like Solmyr, Deemer
  3632. ret *= (100.f + ((caster->valOfBonuses(Bonus::SPECIAL_SPELL_LEV, sp->id) * caster->level) / affectedCreature->getCreature()->level)) / 100.0f;
  3633. }
  3634. return ret;
  3635. }
  3636. ui32 BattleInfo::calculateSpellDmg( const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower ) const
  3637. {
  3638. ui32 ret = 0; //value to return
  3639. //15 - magic arrows, 16 - ice bolt, 17 - lightning bolt, 18 - implosion, 20 - frost ring, 21 - fireball, 22 - inferno, 23 - meteor shower,
  3640. //24 - death ripple, 25 - destroy undead, 26 - armageddon, 77 - thunderbolt
  3641. static std::map <int, int> dmgMultipliers = boost::assign::map_list_of(15, 10)(16, 20)(17, 25)(18, 75)(20, 10)(21, 10)(22, 10)(23, 10)(24, 5)(25, 10)(26, 50)(77, 10);
  3642. //check if spell really does damage - if not, return 0
  3643. if(dmgMultipliers.find(sp->id) == dmgMultipliers.end())
  3644. return 0;
  3645. ret = usedSpellPower * dmgMultipliers[sp->id];
  3646. ret += sp->powers[spellSchoolLevel];
  3647. //affected creature-specific part
  3648. if(affectedCreature)
  3649. {
  3650. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  3651. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
  3652. {
  3653. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 0);
  3654. ret /= 100;
  3655. }
  3656. else if(sp->fire && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
  3657. {
  3658. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 1);
  3659. ret /= 100;
  3660. }
  3661. else if(sp->water && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
  3662. {
  3663. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 2);
  3664. ret /= 100;
  3665. }
  3666. else if (sp->earth && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
  3667. {
  3668. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 3);
  3669. ret /= 100;
  3670. }
  3671. //general spell dmg reduction
  3672. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1)) //air spell & protection from air
  3673. {
  3674. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  3675. ret /= 100;
  3676. }
  3677. //dmg increasing
  3678. if( affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id) )
  3679. {
  3680. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id);
  3681. ret /= 100;
  3682. }
  3683. }
  3684. ret = calculateSpellBonus(ret, sp, caster, affectedCreature);
  3685. return ret;
  3686. }
  3687. ui32 BattleInfo::calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack) const
  3688. {
  3689. int powerPerLevel;
  3690. bool resurrect;
  3691. switch(spell->id)
  3692. {
  3693. case 37: //cure
  3694. {
  3695. powerPerLevel = 5;
  3696. resurrect = false;
  3697. break;
  3698. }
  3699. case 38: //resurrection
  3700. case 39: //animate dead
  3701. {
  3702. powerPerLevel = 50;
  3703. resurrect = true;
  3704. break;
  3705. }
  3706. }
  3707. int healedHealth = caster->getPrimSkillLevel(2) * powerPerLevel + spell->powers[caster->getSpellSchoolLevel(spell)];
  3708. healedHealth = calculateSpellBonus(healedHealth, spell, caster, stack);
  3709. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  3710. }
  3711. bool CGameState::battleCanShoot(int ID, int dest)
  3712. {
  3713. if(!curB)
  3714. return false;
  3715. const CStack *our = curB->getStack(ID),
  3716. *dst = curB->getStackT(dest);
  3717. if(!our || !dst) return false;
  3718. const CGHeroInstance * ourHero = battleGetOwner(our->ID);
  3719. if(our->hasBonusOfType(Bonus::FORGETFULL)) //forgetfulness
  3720. return false;
  3721. if(our->getCreature()->idNumber == 145 && dst) //catapult cannot attack creatures
  3722. return false;
  3723. if(our->hasBonusOfType(Bonus::SHOOTER)//it's shooter
  3724. && our->owner != dst->owner
  3725. && dst->alive()
  3726. && (!curB->isStackBlocked(ID) || NBonus::hasOfType(ourHero, Bonus::FREE_SHOOTING))
  3727. && our->shots
  3728. )
  3729. return true;
  3730. return false;
  3731. }
  3732. int CGameState::victoryCheck( ui8 player ) const
  3733. {
  3734. const PlayerState *p = getPlayer(player);
  3735. if(map->victoryCondition.condition == winStandard || map->victoryCondition.allowNormalVictory)
  3736. if(player == checkForStandardWin())
  3737. return -1;
  3738. if (p->enteredWinningCheatCode)
  3739. { //cheater or tester, but has entered the code...
  3740. return 1;
  3741. }
  3742. if(p->human || map->victoryCondition.appliesToAI)
  3743. {
  3744. switch(map->victoryCondition.condition)
  3745. {
  3746. case artifact:
  3747. //check if any hero has winning artifact
  3748. for(size_t i = 0; i < p->heroes.size(); i++)
  3749. if(p->heroes[i]->hasArt(map->victoryCondition.ID))
  3750. return 1;
  3751. break;
  3752. case gatherTroop:
  3753. {
  3754. //check if in players armies there is enough creatures
  3755. int total = 0; //creature counter
  3756. for(size_t i = 0; i < map->objects.size(); i++)
  3757. {
  3758. const CArmedInstance *ai = NULL;
  3759. if(map->objects[i]
  3760. && map->objects[i]->tempOwner == player //object controlled by player
  3761. && (ai = dynamic_cast<const CArmedInstance*>(map->objects[i].get()))) //contains army
  3762. {
  3763. for(TSlots::const_iterator i=ai->Slots().begin(); i!=ai->Slots().end(); ++i) //iterate through army
  3764. if(i->second->type->idNumber == map->victoryCondition.ID) //it's searched creature
  3765. total += i->second->count;
  3766. }
  3767. }
  3768. if(total >= map->victoryCondition.count)
  3769. return 1;
  3770. }
  3771. break;
  3772. case gatherResource:
  3773. if(p->resources[map->victoryCondition.ID] >= map->victoryCondition.count)
  3774. return 1;
  3775. break;
  3776. case buildCity:
  3777. {
  3778. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  3779. if(t->tempOwner == player && t->fortLevel()-1 >= map->victoryCondition.ID && t->hallLevel()-1 >= map->victoryCondition.count)
  3780. return 1;
  3781. }
  3782. break;
  3783. case buildGrail:
  3784. BOOST_FOREACH(const CGTownInstance *t, map->towns)
  3785. if((t == map->victoryCondition.obj || !map->victoryCondition.obj)
  3786. && t->tempOwner == player
  3787. && vstd::contains(t->builtBuildings, 26))
  3788. return 1;
  3789. break;
  3790. case beatHero:
  3791. if(map->victoryCondition.obj->tempOwner >= PLAYER_LIMIT) //target hero not present on map
  3792. return 1;
  3793. break;
  3794. case captureCity:
  3795. {
  3796. if(map->victoryCondition.obj->tempOwner == player)
  3797. return 1;
  3798. }
  3799. break;
  3800. case beatMonster:
  3801. if(!map->objects[map->victoryCondition.obj->id]) //target monster not present on map
  3802. return 1;
  3803. break;
  3804. case takeDwellings:
  3805. for(size_t i = 0; i < map->objects.size(); i++)
  3806. {
  3807. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  3808. {
  3809. switch(map->objects[i]->ID)
  3810. {
  3811. case 17: case 18: case 19: case 20: //dwellings
  3812. case 216: case 217: case 218:
  3813. return 0; //found not flagged dwelling - player not won
  3814. }
  3815. }
  3816. }
  3817. return 1;
  3818. break;
  3819. case takeMines:
  3820. for(size_t i = 0; i < map->objects.size(); i++)
  3821. {
  3822. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  3823. {
  3824. switch(map->objects[i]->ID)
  3825. {
  3826. case 53: case 220:
  3827. return 0; //found not flagged mine - player not won
  3828. }
  3829. }
  3830. }
  3831. return 1;
  3832. break;
  3833. case transportItem:
  3834. {
  3835. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  3836. if((t->visitingHero && t->visitingHero->hasArt(map->victoryCondition.ID))
  3837. || (t->garrisonHero && t->garrisonHero->hasArt(map->victoryCondition.ID)))
  3838. {
  3839. return 1;
  3840. }
  3841. }
  3842. break;
  3843. }
  3844. }
  3845. return 0;
  3846. }
  3847. ui8 CGameState::checkForStandardWin() const
  3848. {
  3849. //std victory condition is:
  3850. //all enemies lost
  3851. ui8 supposedWinner = 255, winnerTeam = 255;
  3852. for(std::map<ui8,PlayerState>::const_iterator i = players.begin(); i != players.end(); i++)
  3853. {
  3854. if(i->second.status == PlayerState::INGAME && i->first < PLAYER_LIMIT)
  3855. {
  3856. if(supposedWinner == 255)
  3857. {
  3858. //first player remaining ingame - candidate for victory
  3859. supposedWinner = i->second.color;
  3860. winnerTeam = i->second.team;
  3861. }
  3862. else if(winnerTeam != i->second.team)
  3863. {
  3864. //current candidate has enemy remaining in game -> no vicotry
  3865. return 255;
  3866. }
  3867. }
  3868. }
  3869. return supposedWinner;
  3870. }
  3871. bool CGameState::checkForStandardLoss( ui8 player ) const
  3872. {
  3873. //std loss condition is: player lost all towns and heroes
  3874. const PlayerState &p = *getPlayer(player);
  3875. return !p.heroes.size() && !p.towns.size();
  3876. }
  3877. struct statsHLP
  3878. {
  3879. typedef std::pair< ui8, si64 > TStat;
  3880. //converts [<player's color, value>] to vec[place] -> platers
  3881. static std::vector< std::list< ui8 > > getRank( std::vector<TStat> stats )
  3882. {
  3883. std::sort(stats.begin(), stats.end(), statsHLP());
  3884. //put first element
  3885. std::vector< std::list<ui8> > ret;
  3886. std::list<ui8> tmp;
  3887. tmp.push_back( stats[0].first );
  3888. ret.push_back( tmp );
  3889. //the rest of elements
  3890. for(int g=1; g<stats.size(); ++g)
  3891. {
  3892. if(stats[g].second == stats[g-1].second)
  3893. {
  3894. (ret.end()-1)->push_back( stats[g].first );
  3895. }
  3896. else
  3897. {
  3898. //create next occupied rank
  3899. std::list<ui8> tmp;
  3900. tmp.push_back(stats[g].first);
  3901. ret.push_back(tmp);
  3902. }
  3903. }
  3904. return ret;
  3905. }
  3906. bool operator()(const TStat & a, const TStat & b) const
  3907. {
  3908. return a.second > b.second;
  3909. }
  3910. static const CGHeroInstance * findBestHero(CGameState * gs, int color)
  3911. {
  3912. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  3913. if(!h.size())
  3914. return NULL;
  3915. //best hero will be that with highest exp
  3916. int best = 0;
  3917. for(int b=1; b<h.size(); ++b)
  3918. {
  3919. if(h[b]->exp > h[best]->exp)
  3920. {
  3921. best = b;
  3922. }
  3923. }
  3924. return h[best];
  3925. }
  3926. //calculates total number of artifacts that belong to given player
  3927. static int getNumberOfArts(const PlayerState * ps)
  3928. {
  3929. int ret = 0;
  3930. for(int g=0; g<ps->heroes.size(); ++g)
  3931. {
  3932. ret += ps->heroes[g]->artifacts.size() + ps->heroes[g]->artifWorn.size();
  3933. }
  3934. return ret;
  3935. }
  3936. };
  3937. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  3938. {
  3939. #define FILL_FIELD(FIELD, VAL_GETTER) \
  3940. { \
  3941. std::vector< std::pair< ui8, si64 > > stats; \
  3942. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g) \
  3943. { \
  3944. if(g->second.color == 255) \
  3945. continue; \
  3946. std::pair< ui8, si64 > stat; \
  3947. stat.first = g->second.color; \
  3948. stat.second = VAL_GETTER; \
  3949. stats.push_back(stat); \
  3950. } \
  3951. tgi.FIELD = statsHLP::getRank(stats); \
  3952. }
  3953. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  3954. {
  3955. if(g->second.color != 255)
  3956. tgi.playerColors.push_back(g->second.color);
  3957. }
  3958. if(level >= 1) //num of towns & num of heroes
  3959. {
  3960. //num of towns
  3961. FILL_FIELD(numOfTowns, g->second.towns.size())
  3962. //num of heroes
  3963. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  3964. //best hero's portrait
  3965. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  3966. {
  3967. if(g->second.color == 255)
  3968. continue;
  3969. const CGHeroInstance * best = statsHLP::findBestHero(this, g->second.color);
  3970. InfoAboutHero iah;
  3971. iah.initFromHero(best, level >= 8);
  3972. iah.army.clear();
  3973. tgi.colorToBestHero[g->second.color] = iah;
  3974. }
  3975. }
  3976. if(level >= 2) //gold
  3977. {
  3978. FILL_FIELD(gold, g->second.resources[6])
  3979. }
  3980. if(level >= 2) //wood & ore
  3981. {
  3982. FILL_FIELD(woodOre, g->second.resources[0] + g->second.resources[1])
  3983. }
  3984. if(level >= 3) //mercury, sulfur, crystal, gems
  3985. {
  3986. FILL_FIELD(mercSulfCrystGems, g->second.resources[2] + g->second.resources[3] + g->second.resources[4] + g->second.resources[5])
  3987. }
  3988. if(level >= 4) //obelisks found
  3989. {
  3990. //TODO
  3991. }
  3992. if(level >= 5) //artifacts
  3993. {
  3994. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  3995. }
  3996. if(level >= 6) //army strength
  3997. {
  3998. //TODO
  3999. }
  4000. if(level >= 7) //income
  4001. {
  4002. //TODO
  4003. }
  4004. if(level >= 8) //best hero's stats
  4005. {
  4006. //already set in lvl 1 handling
  4007. }
  4008. if(level >= 9) //personality
  4009. {
  4010. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  4011. {
  4012. if(g->second.color == 255) //do nothing for neutral player
  4013. continue;
  4014. if(g->second.human)
  4015. {
  4016. tgi.personality[g->second.color] = -1;
  4017. }
  4018. else //AI
  4019. {
  4020. tgi.personality[g->second.color] = map->players[g->second.color].AITactic;
  4021. }
  4022. }
  4023. }
  4024. if(level >= 10) //best creature
  4025. {
  4026. //best creatures belonging to player (highest AI value)
  4027. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  4028. {
  4029. if(g->second.color == 255) //do nothing for neutral player
  4030. continue;
  4031. int bestCre = -1; //best creature's ID
  4032. for(int b=0; b<g->second.heroes.size(); ++b)
  4033. {
  4034. for(TSlots::const_iterator it = g->second.heroes[b]->Slots().begin(); it != g->second.heroes[b]->Slots().end(); ++it)
  4035. {
  4036. int toCmp = it->second->type->idNumber; //ID of creature we should compare with the best one
  4037. if(bestCre == -1 || VLC->creh->creatures[bestCre]->AIValue < VLC->creh->creatures[toCmp]->AIValue)
  4038. {
  4039. bestCre = toCmp;
  4040. }
  4041. }
  4042. }
  4043. tgi.bestCreature[g->second.color] = bestCre;
  4044. }
  4045. }
  4046. #undef FILL_FIELD
  4047. }
  4048. int CGameState::lossCheck( ui8 player ) const
  4049. {
  4050. const PlayerState *p = getPlayer(player);
  4051. //if(map->lossCondition.typeOfLossCon == lossStandard)
  4052. if(checkForStandardLoss(player))
  4053. return -1;
  4054. if (p->enteredLosingCheatCode)
  4055. {
  4056. return 1;
  4057. }
  4058. if(p->human) //special loss condition applies only to human player
  4059. {
  4060. switch(map->lossCondition.typeOfLossCon)
  4061. {
  4062. case lossCastle:
  4063. {
  4064. const CGTownInstance *t = dynamic_cast<const CGTownInstance *>(map->lossCondition.obj);
  4065. assert(t);
  4066. if(t->tempOwner != player)
  4067. return 1;
  4068. }
  4069. break;
  4070. case lossHero:
  4071. {
  4072. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(map->lossCondition.obj);
  4073. assert(h);
  4074. if(h->tempOwner != player)
  4075. return 1;
  4076. }
  4077. break;
  4078. case timeExpires:
  4079. if(map->lossCondition.timeLimit < day)
  4080. return 1;
  4081. break;
  4082. }
  4083. }
  4084. if(!p->towns.size() && p->daysWithoutCastle >= 7)
  4085. return 2;
  4086. return false;
  4087. }
  4088. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > CGameState::unusedHeroesFromPool()
  4089. {
  4090. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > pool = hpool.heroesPool;
  4091. for ( std::map<ui8, PlayerState>::iterator i = players.begin() ; i != players.end();i++)
  4092. for(std::vector< ConstTransitivePtr<CGHeroInstance> >::iterator j = i->second.availableHeroes.begin(); j != i->second.availableHeroes.end(); j++)
  4093. if(*j)
  4094. pool.erase((**j).subID);
  4095. return pool;
  4096. }
  4097. void CGameState::buildGameLogicTree()
  4098. {
  4099. }
  4100. const CStack * BattleInfo::getNextStack() const
  4101. {
  4102. std::vector<const CStack *> hlp;
  4103. getStackQueue(hlp, 1, -1);
  4104. if(hlp.size())
  4105. return hlp[0];
  4106. else
  4107. return NULL;
  4108. }
  4109. static const CStack *takeStack(std::vector<const CStack *> &st, int &curside, int turn)
  4110. {
  4111. const CStack *ret = NULL;
  4112. unsigned i, //fastest stack
  4113. j; //fastest stack of the other side
  4114. for(i = 0; i < st.size(); i++)
  4115. if(st[i])
  4116. break;
  4117. //no stacks left
  4118. if(i == st.size())
  4119. return NULL;
  4120. const CStack *fastest = st[i], *other = NULL;
  4121. int bestSpeed = fastest->Speed(turn);
  4122. if(fastest->attackerOwned != curside)
  4123. {
  4124. ret = fastest;
  4125. }
  4126. else
  4127. {
  4128. for(j = i + 1; j < st.size(); j++)
  4129. {
  4130. if(!st[j]) continue;
  4131. if(st[j]->attackerOwned != curside || st[j]->Speed(turn) != bestSpeed)
  4132. break;
  4133. }
  4134. if(j >= st.size())
  4135. {
  4136. ret = fastest;
  4137. }
  4138. else
  4139. {
  4140. other = st[j];
  4141. if(other->Speed(turn) != bestSpeed)
  4142. ret = fastest;
  4143. else
  4144. ret = other;
  4145. }
  4146. }
  4147. assert(ret);
  4148. if(ret == fastest)
  4149. st[i] = NULL;
  4150. else
  4151. st[j] = NULL;
  4152. curside = ret->attackerOwned;
  4153. return ret;
  4154. }
  4155. void BattleInfo::getStackQueue( std::vector<const CStack *> &out, int howMany, int turn /*= 0*/, int lastMoved /*= -1*/ ) const
  4156. {
  4157. //we'll split creatures with remaining movement to 4 parts
  4158. std::vector<const CStack *> phase[4]; //0 - turrets/catapult, 1 - normal (unmoved) creatures, other war machines, 2 - waited cres that had morale, 3 - rest of waited cres
  4159. int toMove = 0; //how many stacks still has move
  4160. const CStack *active = getStack(activeStack);
  4161. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  4162. if(!turn && active && active->willMove() && !vstd::contains(active->state, WAITING))
  4163. {
  4164. out.push_back(active);
  4165. if(out.size() == howMany)
  4166. return;
  4167. }
  4168. for(unsigned int i=0; i<stacks.size(); ++i)
  4169. {
  4170. const CStack * const s = stacks[i];
  4171. if(turn <= 0 && !s->willMove() //we are considering current round and stack won't move
  4172. || turn > 0 && !s->canMove(turn) //stack won't be able to move in later rounds
  4173. || turn <= 0 && s == active && out.size() && s == out.front()) //it's active stack already added at the beginning of queue
  4174. {
  4175. continue;
  4176. }
  4177. int p = -1; //in which phase this tack will move?
  4178. if(turn <= 0 && vstd::contains(s->state, WAITING)) //consider waiting state only for ongoing round
  4179. {
  4180. if(vstd::contains(s->state, HAD_MORALE))
  4181. p = 2;
  4182. else
  4183. p = 3;
  4184. }
  4185. else if(s->getCreature()->idNumber == 145 || s->getCreature()->idNumber == 149) //catapult and turrets are first
  4186. {
  4187. p = 0;
  4188. }
  4189. else
  4190. {
  4191. p = 1;
  4192. }
  4193. phase[p].push_back(s);
  4194. toMove++;
  4195. }
  4196. for(int i = 0; i < 4; i++)
  4197. std::sort(phase[i].begin(), phase[i].end(), CMP_stack(i, turn > 0 ? turn : 0));
  4198. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  4199. out.push_back(phase[0][i]);
  4200. if(out.size() == howMany)
  4201. return;
  4202. if(lastMoved == -1)
  4203. {
  4204. if(active)
  4205. {
  4206. if(out.size() && out.front() == active)
  4207. lastMoved = active->attackerOwned;
  4208. else
  4209. lastMoved = active->attackerOwned;
  4210. }
  4211. else
  4212. {
  4213. lastMoved = 0;
  4214. }
  4215. }
  4216. int pi = 1;
  4217. while(out.size() < howMany)
  4218. {
  4219. const CStack *hlp = takeStack(phase[pi], lastMoved, turn);
  4220. if(!hlp)
  4221. {
  4222. pi++;
  4223. if(pi > 3)
  4224. {
  4225. //if(turn != 2)
  4226. getStackQueue(out, howMany, turn + 1, lastMoved);
  4227. return;
  4228. }
  4229. }
  4230. else
  4231. {
  4232. out.push_back(hlp);
  4233. }
  4234. }
  4235. }
  4236. si8 BattleInfo::hasDistancePenalty( int stackID, int destHex )
  4237. {
  4238. const CStack * stack = getStack(stackID);
  4239. struct HLP
  4240. {
  4241. static bool lowerAnalyze(const CStack * stack, int hex)
  4242. {
  4243. int distance = BattleInfo::getDistance(hex, stack->position);
  4244. //I hope it's approximately correct
  4245. return distance > 10 && !stack->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY);
  4246. }
  4247. };
  4248. const CStack * dstStack = getStackT(destHex, false);
  4249. if (dstStack->doubleWide())
  4250. return HLP::lowerAnalyze(stack, destHex) && HLP::lowerAnalyze(stack, dstStack->occupiedHex());
  4251. else
  4252. return HLP::lowerAnalyze(stack, destHex);
  4253. }
  4254. si8 BattleInfo::sameSideOfWall(int pos1, int pos2)
  4255. {
  4256. int wallInStackLine = lineToWallHex(pos1/BFIELD_WIDTH);
  4257. int wallInDestLine = lineToWallHex(pos2/BFIELD_WIDTH);
  4258. bool stackLeft = pos1 < wallInStackLine;
  4259. bool destLeft = pos2 < wallInDestLine;
  4260. return stackLeft != destLeft;
  4261. }
  4262. si8 BattleInfo::hasWallPenalty( int stackID, int destHex )
  4263. {
  4264. if (siege == 0)
  4265. {
  4266. return false;
  4267. }
  4268. const CStack * stack = getStack(stackID);
  4269. if (stack->hasBonusOfType(Bonus::NO_WALL_PENALTY))
  4270. {
  4271. return false;
  4272. }
  4273. return !sameSideOfWall(stack->position, destHex);
  4274. }
  4275. si8 BattleInfo::canTeleportTo(int stackID, int destHex, int telportLevel)
  4276. {
  4277. bool ac[BFIELD_SIZE];
  4278. const CStack *s = getStack(stackID, false); //this function is called from healedOrResurrected, so our stack can be dead
  4279. std::set<int> occupyable;
  4280. getAccessibilityMap(ac, s->doubleWide(), s->attackerOwned, false, occupyable, s->hasBonusOfType(Bonus::FLYING), stackID);
  4281. if (siege && telportLevel < 2) //check for wall
  4282. {
  4283. return ac[destHex] && sameSideOfWall(s->position, destHex);
  4284. }
  4285. else
  4286. {
  4287. return ac[destHex];
  4288. }
  4289. }
  4290. // void BattleInfo::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  4291. // {
  4292. // CBonusSystemNode::getBonuses(out, selector, root);
  4293. //
  4294. // const CStack *dest = dynamic_cast<const CStack*>(root);
  4295. // if (!dest)
  4296. // return;
  4297. //
  4298. // //TODO: make it in clean way
  4299. // if(Selector::matchesType(selector, Bonus::MORALE) || Selector::matchesType(selector, Bonus::LUCK))
  4300. // {
  4301. // BOOST_FOREACH(const CStack *s, stacks)
  4302. // {
  4303. // if(s->owner == dest->owner)
  4304. // s->getBonuses(out, selector, Selector::effectRange(Bonus::ONLY_ALLIED_ARMY), this);
  4305. // else
  4306. // s->getBonuses(out, selector, Selector::effectRange(Bonus::ONLY_ENEMY_ARMY), this);
  4307. // }
  4308. // }
  4309. // }
  4310. si8 BattleInfo::getDistance( THex hex1, THex hex2 )
  4311. {
  4312. int xDst = std::abs(hex1 % BFIELD_WIDTH - hex2 % BFIELD_WIDTH),
  4313. yDst = std::abs(hex1 / BFIELD_WIDTH - hex2 / BFIELD_WIDTH);
  4314. return std::max(xDst, yDst) + std::min(xDst, yDst) - (yDst + 1)/2;
  4315. }
  4316. void BattleInfo::localInit()
  4317. {
  4318. belligerents[0]->battle = belligerents[1]->battle = this;
  4319. //TODO: attach battle to belligerents
  4320. BOOST_FOREACH(CStack *s, stacks)
  4321. {
  4322. if(s->base) //stack originating from "real" stack in garrison -> attach to it
  4323. {
  4324. s->attachTo(const_cast<CStackInstance*>(s->base));
  4325. }
  4326. else //attach directly to obj to which stack belongs and creature type
  4327. {
  4328. CArmedInstance *army = belligerents[!s->attackerOwned];
  4329. s->attachTo(army);
  4330. assert(s->type);
  4331. s->attachTo(const_cast<CCreature*>(s->type));
  4332. }
  4333. s->postInit();
  4334. }
  4335. }
  4336. int3 CPath::startPos() const
  4337. {
  4338. return nodes[nodes.size()-1].coord;
  4339. }
  4340. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  4341. {
  4342. if (mode==0)
  4343. {
  4344. for (unsigned int i=0;i<nodes.size();i++)
  4345. {
  4346. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  4347. }
  4348. }
  4349. }
  4350. int3 CPath::endPos() const
  4351. {
  4352. return nodes[0].coord;
  4353. }
  4354. CGPathNode::CGPathNode()
  4355. :coord(-1,-1,-1)
  4356. {
  4357. accessible = 0;
  4358. land = 0;
  4359. moveRemains = 0;
  4360. turns = 255;
  4361. theNodeBefore = NULL;
  4362. }
  4363. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  4364. {
  4365. out.nodes.clear();
  4366. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  4367. if(!curnode->theNodeBefore || curnode->accessible == CGPathNode::FLYABLE)
  4368. return false;
  4369. //we'll transform number of turns to conform the rule that hero cannot stop on blocked tile
  4370. bool transition01 = false;
  4371. while(curnode)
  4372. {
  4373. CGPathNode cpn = *curnode;
  4374. if(transition01)
  4375. {
  4376. if (curnode->accessible == CGPathNode::ACCESSIBLE)
  4377. {
  4378. transition01 = false;
  4379. }
  4380. else if (curnode->accessible == CGPathNode::FLYABLE)
  4381. {
  4382. cpn.turns = 1;
  4383. }
  4384. }
  4385. if(curnode->turns == 1 && curnode->theNodeBefore->turns == 0)
  4386. {
  4387. transition01 = true;
  4388. }
  4389. curnode = curnode->theNodeBefore;
  4390. out.nodes.push_back(cpn);
  4391. }
  4392. return true;
  4393. }
  4394. CPathsInfo::CPathsInfo( const int3 &Sizes )
  4395. :sizes(Sizes)
  4396. {
  4397. hero = NULL;
  4398. nodes = new CGPathNode**[sizes.x];
  4399. for(int i = 0; i < sizes.x; i++)
  4400. {
  4401. nodes[i] = new CGPathNode*[sizes.y];
  4402. for (int j = 0; j < sizes.y; j++)
  4403. {
  4404. nodes[i][j] = new CGPathNode[sizes.z];
  4405. }
  4406. }
  4407. }
  4408. CPathsInfo::~CPathsInfo()
  4409. {
  4410. for(int i = 0; i < sizes.x; i++)
  4411. {
  4412. for (int j = 0; j < sizes.y; j++)
  4413. {
  4414. delete [] nodes[i][j];
  4415. }
  4416. delete [] nodes[i];
  4417. }
  4418. delete [] nodes;
  4419. }
  4420. int3 CGPath::startPos() const
  4421. {
  4422. return nodes[nodes.size()-1].coord;
  4423. }
  4424. int3 CGPath::endPos() const
  4425. {
  4426. return nodes[0].coord;
  4427. }
  4428. void CGPath::convert( ui8 mode )
  4429. {
  4430. if(mode==0)
  4431. {
  4432. for(unsigned int i=0;i<nodes.size();i++)
  4433. {
  4434. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  4435. }
  4436. }
  4437. }
  4438. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  4439. {
  4440. switch(phase)
  4441. {
  4442. case 0: //catapult moves after turrets
  4443. return a->getCreature()->idNumber < b->getCreature()->idNumber; //catapult is 145 and turrets are 149
  4444. //TODO? turrets order
  4445. case 1: //fastest first, upper slot first
  4446. {
  4447. int as = a->Speed(turn), bs = b->Speed(turn);
  4448. if(as != bs)
  4449. return as > bs;
  4450. else
  4451. return a->slot < b->slot;
  4452. }
  4453. case 2: //fastest last, upper slot first
  4454. //TODO: should be replaced with order of receiving morale!
  4455. case 3: //fastest last, upper slot first
  4456. {
  4457. int as = a->Speed(turn), bs = b->Speed(turn);
  4458. if(as != bs)
  4459. return as < bs;
  4460. else
  4461. return a->slot < b->slot;
  4462. }
  4463. default:
  4464. assert(0);
  4465. return false;
  4466. }
  4467. }
  4468. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  4469. {
  4470. phase = Phase;
  4471. turn = Turn;
  4472. }
  4473. PlayerState::PlayerState()
  4474. : color(-1), currentSelection(0xffffffff), enteredWinningCheatCode(0),
  4475. enteredLosingCheatCode(0), status(INGAME), daysWithoutCastle(0)
  4476. {
  4477. }
  4478. std::string PlayerState::nodeName() const
  4479. {
  4480. return "Player " + (color < VLC->generaltexth->capColors.size() ? VLC->generaltexth->capColors[color] : boost::lexical_cast<std::string>(color));
  4481. }
  4482. // void PlayerState::getParents(TCNodes &out, const CBonusSystemNode *root /*= NULL*/) const
  4483. // {
  4484. // return; //no loops possible
  4485. // }
  4486. //
  4487. // void PlayerState::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  4488. // {
  4489. // for (std::vector<CGHeroInstance *>::const_iterator it = heroes.begin(); it != heroes.end(); it++)
  4490. // {
  4491. // if (*it != root)
  4492. // (*it)->getBonuses(out, selector, this);
  4493. // }
  4494. // }
  4495. InfoAboutHero::InfoAboutHero()
  4496. {
  4497. details = NULL;
  4498. hclass = NULL;
  4499. portrait = -1;
  4500. }
  4501. InfoAboutHero::InfoAboutHero( const InfoAboutHero & iah )
  4502. {
  4503. assign(iah);
  4504. }
  4505. InfoAboutHero::~InfoAboutHero()
  4506. {
  4507. delete details;
  4508. }
  4509. void InfoAboutHero::initFromHero( const CGHeroInstance *h, bool detailed )
  4510. {
  4511. if(!h) return;
  4512. owner = h->tempOwner;
  4513. hclass = h->type->heroClass;
  4514. name = h->name;
  4515. portrait = h->portrait;
  4516. army = ArmyDescriptor(h, detailed);
  4517. if(detailed)
  4518. {
  4519. //include details about hero
  4520. details = new Details;
  4521. details->luck = h->LuckVal();
  4522. details->morale = h->MoraleVal();
  4523. details->mana = h->mana;
  4524. details->primskills.resize(PRIMARY_SKILLS);
  4525. for (int i = 0; i < PRIMARY_SKILLS ; i++)
  4526. {
  4527. details->primskills[i] = h->getPrimSkillLevel(i);
  4528. }
  4529. }
  4530. }
  4531. void InfoAboutHero::assign( const InfoAboutHero & iah )
  4532. {
  4533. army = iah.army;
  4534. details = (iah.details ? new Details(*iah.details) : NULL);
  4535. hclass = iah.hclass;
  4536. name = iah.name;
  4537. owner = iah.owner;
  4538. portrait = iah.portrait;
  4539. }
  4540. InfoAboutHero & InfoAboutHero::operator=( const InfoAboutHero & iah )
  4541. {
  4542. assign(iah);
  4543. return *this;
  4544. }
  4545. ArmyDescriptor::ArmyDescriptor(const CArmedInstance *army, bool detailed)
  4546. {
  4547. for(TSlots::const_iterator i = army->Slots().begin(); i != army->Slots().end(); i++)
  4548. {
  4549. if(detailed)
  4550. (*this)[i->first] = *i->second;
  4551. else
  4552. (*this)[i->first] = CStackBasicDescriptor(i->second->type, i->second->getQuantityID());
  4553. }
  4554. }
  4555. ArmyDescriptor::ArmyDescriptor()
  4556. {
  4557. }