CGameState.cpp 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934
  1. #define VCMI_DLL
  2. #include "../hch/CCampaignHandler.h"
  3. #include <algorithm>
  4. #include <queue>
  5. #include <fstream>
  6. #include "CGameState.h"
  7. #include <boost/random/linear_congruential.hpp>
  8. #include "../hch/CDefObjInfoHandler.h"
  9. #include "../hch/CArtHandler.h"
  10. #include "../hch/CBuildingHandler.h"
  11. #include "../hch/CGeneralTextHandler.h"
  12. #include "../hch/CTownHandler.h"
  13. #include "../hch/CSpellHandler.h"
  14. #include "../hch/CHeroHandler.h"
  15. #include "../hch/CObjectHandler.h"
  16. #include "../hch/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. boost::rand48 ran;
  32. class CGObjectInstance;
  33. #ifdef min
  34. #undef min
  35. #endif
  36. #ifdef max
  37. #undef max
  38. #endif
  39. /*
  40. * CGameState.cpp, part of VCMI engine
  41. *
  42. * Authors: listed in file AUTHORS in main folder
  43. *
  44. * License: GNU General Public License v2.0 or later
  45. * Full text of license available in license.txt file, in main folder
  46. *
  47. */
  48. void foofoofoo()
  49. {
  50. //never called function to force instantation of templates
  51. int *ccc = NULL;
  52. registerTypes((CISer<CConnection>&)*ccc);
  53. registerTypes((COSer<CConnection>&)*ccc);
  54. registerTypes((CSaveFile&)*ccc);
  55. registerTypes((CLoadFile&)*ccc);
  56. registerTypes((CTypeList&)*ccc);
  57. }
  58. class CBaseForGSApply
  59. {
  60. public:
  61. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  62. virtual ~CBaseForGSApply(){};
  63. };
  64. template <typename T> class CApplyOnGS : public CBaseForGSApply
  65. {
  66. public:
  67. void applyOnGS(CGameState *gs, void *pack) const
  68. {
  69. T *ptr = static_cast<T*>(pack);
  70. while(!gs->mx->try_lock())
  71. boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  72. ptr->applyGs(gs);
  73. gs->mx->unlock();
  74. }
  75. };
  76. class CGSApplier
  77. {
  78. public:
  79. std::map<ui16,CBaseForGSApply*> apps;
  80. CGSApplier()
  81. {
  82. registerTypes2(*this);
  83. }
  84. ~CGSApplier()
  85. {
  86. std::map<ui16,CBaseForGSApply*>::iterator iter;
  87. for(iter = apps.begin(); iter != apps.end(); iter++)
  88. delete iter->second;
  89. }
  90. template<typename T> void registerType(const T * t=NULL)
  91. {
  92. ui16 ID = typeList.registerType(t);
  93. apps[ID] = new CApplyOnGS<T>;
  94. }
  95. } *applierGs = NULL;
  96. class IObjectCaller
  97. {
  98. public:
  99. virtual void preInit()=0;
  100. virtual void postInit()=0;
  101. };
  102. template <typename T>
  103. class CObjectCaller : public IObjectCaller
  104. {
  105. public:
  106. void preInit()
  107. {
  108. T::preInit();
  109. }
  110. void postInit()
  111. {
  112. T::postInit();
  113. }
  114. };
  115. class CObjectCallersHandler
  116. {
  117. public:
  118. std::vector<IObjectCaller*> apps;
  119. template<typename T> void registerType(const T * t=NULL)
  120. {
  121. apps.push_back(new CObjectCaller<T>);
  122. }
  123. CObjectCallersHandler()
  124. {
  125. registerTypes1(*this);
  126. }
  127. ~CObjectCallersHandler()
  128. {
  129. for (size_t i = 0; i < apps.size(); i++)
  130. delete apps[i];
  131. }
  132. void preInit()
  133. {
  134. for (size_t i = 0; i < apps.size(); i++)
  135. apps[i]->preInit();
  136. }
  137. void postInit()
  138. {
  139. for (size_t i = 0; i < apps.size(); i++)
  140. apps[i]->postInit();
  141. }
  142. } *objCaller = NULL;
  143. void MetaString::getLocalString(const std::pair<ui8,ui32> &txt, std::string &dst) const
  144. {
  145. int type = txt.first, ser = txt.second;
  146. if(type == ART_NAMES)
  147. {
  148. dst = VLC->arth->artifacts[ser]->Name();
  149. }
  150. else if(type == CRE_PL_NAMES)
  151. {
  152. dst = VLC->creh->creatures[ser]->namePl;
  153. }
  154. else if(type == MINE_NAMES)
  155. {
  156. dst = VLC->generaltexth->mines[ser].first;
  157. }
  158. else if(type == MINE_EVNTS)
  159. {
  160. dst = VLC->generaltexth->mines[ser].second;
  161. }
  162. else if(type == SPELL_NAME)
  163. {
  164. dst = VLC->spellh->spells[ser].name;
  165. }
  166. else if(type == CRE_SING_NAMES)
  167. {
  168. dst = VLC->creh->creatures[ser]->nameSing;
  169. }
  170. else if(type == ART_DESCR)
  171. {
  172. dst = VLC->arth->artifacts[ser]->Description();
  173. }
  174. else
  175. {
  176. std::vector<std::string> *vec;
  177. switch(type)
  178. {
  179. case GENERAL_TXT:
  180. vec = &VLC->generaltexth->allTexts;
  181. break;
  182. case XTRAINFO_TXT:
  183. vec = &VLC->generaltexth->xtrainfo;
  184. break;
  185. case OBJ_NAMES:
  186. vec = &VLC->generaltexth->names;
  187. break;
  188. case RES_NAMES:
  189. vec = &VLC->generaltexth->restypes;
  190. break;
  191. case ARRAY_TXT:
  192. vec = &VLC->generaltexth->arraytxt;
  193. break;
  194. case CREGENS:
  195. vec = &VLC->generaltexth->creGens;
  196. break;
  197. case CREGENS4:
  198. vec = &VLC->generaltexth->creGens4;
  199. break;
  200. case ADVOB_TXT:
  201. vec = &VLC->generaltexth->advobtxt;
  202. break;
  203. case ART_EVNTS:
  204. vec = &VLC->generaltexth->artifEvents;
  205. break;
  206. case SEC_SKILL_NAME:
  207. vec = &VLC->generaltexth->skillName;
  208. break;
  209. case COLOR:
  210. vec = &VLC->generaltexth->capColors;
  211. break;
  212. }
  213. dst = (*vec)[ser];
  214. }
  215. }
  216. DLL_EXPORT void MetaString::toString(std::string &dst) const
  217. {
  218. size_t exSt = 0, loSt = 0, nums = 0;
  219. dst.clear();
  220. for(size_t i=0;i<message.size();++i)
  221. {//TEXACT_STRING, TLOCAL_STRING, TNUMBER, TREPLACE_ESTRING, TREPLACE_LSTRING, TREPLACE_NUMBER
  222. switch(message[i])
  223. {
  224. case TEXACT_STRING:
  225. dst += exactStrings[exSt++];
  226. break;
  227. case TLOCAL_STRING:
  228. {
  229. std::string hlp;
  230. getLocalString(localStrings[loSt++], hlp);
  231. dst += hlp;
  232. }
  233. break;
  234. case TNUMBER:
  235. dst += boost::lexical_cast<std::string>(numbers[nums++]);
  236. break;
  237. case TREPLACE_ESTRING:
  238. dst.replace (dst.find("%s"), 2, exactStrings[exSt++]);
  239. break;
  240. case TREPLACE_LSTRING:
  241. {
  242. std::string hlp;
  243. getLocalString(localStrings[loSt++], hlp);
  244. dst.replace (dst.find("%s"), 2, hlp);
  245. }
  246. break;
  247. case TREPLACE_NUMBER:
  248. dst.replace (dst.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  249. break;
  250. default:
  251. tlog1 << "MetaString processing error!\n";
  252. break;
  253. }
  254. }
  255. }
  256. DLL_EXPORT std::string MetaString::buildList () const
  257. ///used to handle loot from creature bank
  258. {
  259. size_t exSt = 0, loSt = 0, nums = 0;
  260. std::string lista;
  261. for (int i = 0; i < message.size(); ++i)
  262. {
  263. if (i > 0 && message[i] == TEXACT_STRING || message[i] == TLOCAL_STRING)
  264. {
  265. if (exSt == exactStrings.size() - 1)
  266. lista += VLC->generaltexth->allTexts[141]; //" and "
  267. else
  268. lista += ", ";
  269. }
  270. switch (message[i])
  271. {
  272. case TEXACT_STRING:
  273. lista += exactStrings[exSt++];
  274. break;
  275. case TLOCAL_STRING:
  276. {
  277. std::string hlp;
  278. getLocalString (localStrings[loSt++], hlp);
  279. lista += hlp;
  280. }
  281. break;
  282. case TNUMBER:
  283. lista += boost::lexical_cast<std::string>(numbers[nums++]);
  284. break;
  285. case TREPLACE_ESTRING:
  286. lista.replace (lista.find("%s"), 2, exactStrings[exSt++]);
  287. break;
  288. case TREPLACE_LSTRING:
  289. {
  290. std::string hlp;
  291. getLocalString (localStrings[loSt++], hlp);
  292. lista.replace (lista.find("%s"), 2, hlp);
  293. }
  294. break;
  295. case TREPLACE_NUMBER:
  296. lista.replace (lista.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  297. break;
  298. default:
  299. tlog1 << "MetaString processing error!\n";
  300. }
  301. }
  302. return lista;
  303. }
  304. void MetaString::addReplacement(const CStackInstance &stack)
  305. {
  306. assert(stack.count); //valid count
  307. assert(stack.type); //valid type
  308. if (stack.count == 1)
  309. addReplacement (CRE_SING_NAMES, stack.type->idNumber);
  310. else
  311. addReplacement (CRE_PL_NAMES, stack.type->idNumber);
  312. }
  313. static CGObjectInstance * createObject(int id, int subid, int3 pos, int owner)
  314. {
  315. CGObjectInstance * nobj;
  316. switch(id)
  317. {
  318. case HEROI_TYPE: //hero
  319. {
  320. CGHeroInstance * nobj = new CGHeroInstance();
  321. nobj->pos = pos;
  322. nobj->tempOwner = owner;
  323. nobj->subID = subid;
  324. //nobj->initHero(ran);
  325. return nobj;
  326. }
  327. case TOWNI_TYPE: //town
  328. nobj = new CGTownInstance;
  329. break;
  330. default: //rest of objects
  331. nobj = new CGObjectInstance;
  332. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  333. break;
  334. }
  335. nobj->ID = id;
  336. nobj->subID = subid;
  337. if(!nobj->defInfo)
  338. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  339. nobj->pos = pos;
  340. //nobj->state = NULL;//new CLuaObjectScript();
  341. nobj->tempOwner = owner;
  342. nobj->defInfo->id = id;
  343. nobj->defInfo->subid = subid;
  344. //assigning defhandler
  345. if(nobj->ID==HEROI_TYPE || nobj->ID==TOWNI_TYPE)
  346. return nobj;
  347. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  348. return nobj;
  349. }
  350. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  351. {
  352. for(unsigned int g=0; g<stacks.size(); ++g)
  353. {
  354. if(stacks[g]->ID == stackID && (!onlyAlive || stacks[g]->alive()))
  355. return stacks[g];
  356. }
  357. return NULL;
  358. }
  359. const CStack * BattleInfo::getStack(int stackID, bool onlyAlive) const
  360. {
  361. return const_cast<BattleInfo * const>(this)->getStack(stackID, onlyAlive);
  362. }
  363. CStack * BattleInfo::getStackT(int tileID, bool onlyAlive)
  364. {
  365. for(unsigned int g=0; g<stacks.size(); ++g)
  366. {
  367. if(stacks[g]->position == tileID
  368. || (stacks[g]->doubleWide() && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  369. || (stacks[g]->doubleWide() && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  370. {
  371. if(!onlyAlive || stacks[g]->alive())
  372. {
  373. return stacks[g];
  374. }
  375. }
  376. }
  377. return NULL;
  378. }
  379. const CStack * BattleInfo::getStackT(int tileID, bool onlyAlive) const
  380. {
  381. return const_cast<BattleInfo * const>(this)->getStackT(tileID, onlyAlive);
  382. }
  383. void BattleInfo::getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<int> & occupyable, bool flying, int stackToOmmit) const
  384. {
  385. memset(accessibility, 1, BFIELD_SIZE); //initialize array with trues
  386. //removing accessibility for side columns of hexes
  387. for(int v = 0; v < BFIELD_SIZE; ++v)
  388. {
  389. if( v % BFIELD_WIDTH == 0 || v % BFIELD_WIDTH == (BFIELD_WIDTH - 1) )
  390. accessibility[v] = false;
  391. }
  392. for(unsigned int g=0; g<stacks.size(); ++g)
  393. {
  394. 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)
  395. continue;
  396. accessibility[stacks[g]->position] = false;
  397. if(stacks[g]->doubleWide()) //if it's a double hex creature
  398. {
  399. if(stacks[g]->attackerOwned)
  400. accessibility[stacks[g]->position-1] = false;
  401. else
  402. accessibility[stacks[g]->position+1] = false;
  403. }
  404. }
  405. //obstacles
  406. for(unsigned int b=0; b<obstacles.size(); ++b)
  407. {
  408. std::vector<int> blocked = VLC->heroh->obstacles[obstacles[b].ID].getBlocked(obstacles[b].pos);
  409. for(unsigned int c=0; c<blocked.size(); ++c)
  410. {
  411. if(blocked[c] >=0 && blocked[c] < BFIELD_SIZE)
  412. accessibility[blocked[c]] = false;
  413. }
  414. }
  415. //walls
  416. if(siege > 0)
  417. {
  418. static const int permanentlyLocked[] = {12, 45, 78, 112, 147, 165};
  419. for(int b=0; b<ARRAY_COUNT(permanentlyLocked); ++b)
  420. {
  421. accessibility[permanentlyLocked[b]] = false;
  422. }
  423. static const std::pair<int, int> lockedIfNotDestroyed[] = //(which part of wall, which hex is blocked if this part of wall is not destroyed
  424. {std::make_pair(2, 182), std::make_pair(3, 130), std::make_pair(4, 62), std::make_pair(5, 29)};
  425. for(int b=0; b<ARRAY_COUNT(lockedIfNotDestroyed); ++b)
  426. {
  427. if(si.wallState[lockedIfNotDestroyed[b].first] < 3)
  428. {
  429. accessibility[lockedIfNotDestroyed[b].second] = false;
  430. }
  431. }
  432. //gate
  433. if(attackerOwned && si.wallState[7] < 3) //if it attacker's unit and gate is not destroyed
  434. {
  435. accessibility[95] = accessibility[96] = false; //block gate's hexes
  436. }
  437. }
  438. //occupyability
  439. if(addOccupiable && twoHex)
  440. {
  441. std::set<int> rem; //tiles to unlock
  442. for(int h=0; h<BFIELD_HEIGHT; ++h)
  443. {
  444. for(int w=1; w<BFIELD_WIDTH-1; ++w)
  445. {
  446. int hex = h * BFIELD_WIDTH + w;
  447. if(!isAccessible(hex, accessibility, twoHex, attackerOwned, flying, true)
  448. && (attackerOwned ? isAccessible(hex+1, accessibility, twoHex, attackerOwned, flying, true) : isAccessible(hex-1, accessibility, twoHex, attackerOwned, flying, true) )
  449. )
  450. rem.insert(hex);
  451. }
  452. }
  453. occupyable = rem;
  454. /*for(std::set<int>::const_iterator it = rem.begin(); it != rem.end(); ++it)
  455. {
  456. accessibility[*it] = true;
  457. }*/
  458. }
  459. }
  460. bool BattleInfo::isAccessible(int hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos)
  461. {
  462. if(flying && !lastPos)
  463. return true;
  464. if(twoHex)
  465. {
  466. //if given hex is accessible and appropriate adjacent one is free too
  467. return accessibility[hex] && accessibility[hex + (attackerOwned ? -1 : 1 )];
  468. }
  469. else
  470. {
  471. return accessibility[hex];
  472. }
  473. }
  474. 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
  475. {
  476. //inits
  477. for(int b=0; b<BFIELD_SIZE; ++b)
  478. predecessor[b] = -1;
  479. for(int g=0; g<BFIELD_SIZE; ++g)
  480. dists[g] = 100000000;
  481. std::queue< std::pair<int, bool> > hexq; //bfs queue <hex, accessible> (second filed used only if fillPredecessors is true)
  482. hexq.push(std::make_pair(start, true));
  483. dists[hexq.front().first] = 0;
  484. int curNext = -1; //for bfs loop only (helper var)
  485. while(!hexq.empty()) //bfs loop
  486. {
  487. std::pair<int, bool> curHex = hexq.front();
  488. std::vector<int> neighbours = neighbouringTiles(curHex.first);
  489. hexq.pop();
  490. for(unsigned int nr=0; nr<neighbours.size(); nr++)
  491. {
  492. curNext = neighbours[nr]; //if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  493. bool accessible = isAccessible(curNext, accessibility, twoHex, attackerOwned, flying, dists[curHex.first]+1 == dists[curNext]);
  494. if( dists[curHex.first]+1 >= dists[curNext] )
  495. continue;
  496. if(accessible && curHex.second)
  497. {
  498. hexq.push(std::make_pair(curNext, true));
  499. dists[curNext] = dists[curHex.first] + 1;
  500. }
  501. else if(fillPredecessors && !(accessible && !curHex.second))
  502. {
  503. hexq.push(std::make_pair(curNext, false));
  504. dists[curNext] = dists[curHex.first] + 1;
  505. }
  506. predecessor[curNext] = curHex.first;
  507. }
  508. }
  509. };
  510. std::vector<int> BattleInfo::getAccessibility(int stackID, bool addOccupiable) const
  511. {
  512. std::vector<int> ret;
  513. bool ac[BFIELD_SIZE];
  514. const CStack *s = getStack(stackID, false); //this function is called from healedOrResurrected, so our stack can be dead
  515. if(s->position < 0) //turrets
  516. return std::vector<int>();
  517. std::set<int> occupyable;
  518. getAccessibilityMap(ac, s->doubleWide(), s->attackerOwned, addOccupiable, occupyable, s->hasBonusOfType(Bonus::FLYING), stackID);
  519. int pr[BFIELD_SIZE], dist[BFIELD_SIZE];
  520. makeBFS(s->position, ac, pr, dist, s->doubleWide(), s->attackerOwned, s->hasBonusOfType(Bonus::FLYING), false);
  521. if(s->doubleWide())
  522. {
  523. if(!addOccupiable)
  524. {
  525. std::vector<int> rem;
  526. for(int b=0; b<BFIELD_SIZE; ++b)
  527. {
  528. //don't take into account most left and most right columns of hexes
  529. if( b % BFIELD_WIDTH == 0 || b % BFIELD_WIDTH == BFIELD_WIDTH - 1 )
  530. continue;
  531. if( ac[b] && !(s->attackerOwned ? ac[b-1] : ac[b+1]) )
  532. {
  533. rem.push_back(b);
  534. }
  535. }
  536. for(unsigned int g=0; g<rem.size(); ++g)
  537. {
  538. ac[rem[g]] = false;
  539. }
  540. //removing accessibility for side hexes
  541. for(int v=0; v<BFIELD_SIZE; ++v)
  542. if(s->attackerOwned ? (v%BFIELD_WIDTH)==1 : (v%BFIELD_WIDTH)==(BFIELD_WIDTH - 2))
  543. ac[v] = false;
  544. }
  545. }
  546. for (int i=0; i < BFIELD_SIZE ; ++i) {
  547. if(
  548. ( ( !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
  549. || (vstd::contains(occupyable, i) && ( dist[ i + (s->attackerOwned ? 1 : -1 ) ] <= s->Speed() ) &&
  550. ac[i + (s->attackerOwned ? 1 : -1 )] ) //it's occupyable and we can reach adjacent hex
  551. )
  552. {
  553. ret.push_back(i);
  554. }
  555. }
  556. return ret;
  557. }
  558. bool BattleInfo::isStackBlocked(int ID)
  559. {
  560. CStack *our = getStack(ID);
  561. if(our->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  562. return false;
  563. for(unsigned int i=0; i<stacks.size();i++)
  564. {
  565. if( !stacks[i]->alive()
  566. || stacks[i]->owner==our->owner
  567. )
  568. continue; //we omit dead and allied stacks
  569. if(stacks[i]->doubleWide())
  570. {
  571. if( mutualPosition(stacks[i]->position, our->position) >= 0
  572. || mutualPosition(stacks[i]->position + (stacks[i]->attackerOwned ? -1 : 1), our->position) >= 0)
  573. return true;
  574. }
  575. else
  576. {
  577. if( mutualPosition(stacks[i]->position, our->position) >= 0 )
  578. return true;
  579. }
  580. }
  581. return false;
  582. }
  583. signed char BattleInfo::mutualPosition(int hex1, int hex2)
  584. {
  585. if(hex2 == hex1 - ( (hex1/17)%2 ? 18 : 17 )) //top left
  586. return 0;
  587. if(hex2 == hex1 - ( (hex1/17)%2 ? 17 : 16 )) //top right
  588. return 1;
  589. if(hex2 == hex1 - 1 && hex1%17 != 0) //left
  590. return 5;
  591. if(hex2 == hex1 + 1 && hex1%17 != 16) //right
  592. return 2;
  593. if(hex2 == hex1 + ( (hex1/17)%2 ? 16 : 17 )) //bottom left
  594. return 4;
  595. if(hex2 == hex1 + ( (hex1/17)%2 ? 17 : 18 )) //bottom right
  596. return 3;
  597. return -1;
  598. }
  599. std::vector<int> BattleInfo::neighbouringTiles(int hex)
  600. {
  601. #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);}
  602. std::vector<int> ret;
  603. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 18 : 17 ));
  604. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 17 : 16 ));
  605. CHECK_AND_PUSH(hex - 1);
  606. CHECK_AND_PUSH(hex + 1);
  607. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 16 : 17 ));
  608. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 17 : 18 ));
  609. #undef CHECK_AND_PUSH
  610. return ret;
  611. }
  612. std::pair< std::vector<int>, int > BattleInfo::getPath(int start, int dest, bool*accessibility, bool flyingCreature, bool twoHex, bool attackerOwned)
  613. {
  614. int predecessor[BFIELD_SIZE]; //for getting the Path
  615. int dist[BFIELD_SIZE]; //calculated distances
  616. makeBFS(start, accessibility, predecessor, dist, twoHex, attackerOwned, flyingCreature, false);
  617. if(predecessor[dest] == -1) //cannot reach destination
  618. {
  619. return std::make_pair(std::vector<int>(), 0);
  620. }
  621. //making the Path
  622. std::vector<int> path;
  623. int curElem = dest;
  624. while(curElem != start)
  625. {
  626. path.push_back(curElem);
  627. curElem = predecessor[curElem];
  628. }
  629. return std::make_pair(path, dist[dest]);
  630. }
  631. CStack::CStack(const CStackInstance *base, int O, int I, bool AO, int S)
  632. : CStackInstance(*base), ID(I), owner(O), slot(S), attackerOwned(AO), position(-1),
  633. counterAttacks(1)
  634. {
  635. baseAmount = base->count;
  636. firstHPleft = valOfBonuses(Bonus::STACK_HEALTH);
  637. shots = type->shots;
  638. counterAttacks += valOfBonuses(Bonus::ADDITIONAL_RETALIATION);
  639. //alive state indication
  640. state.insert(ALIVE);
  641. }
  642. ui32 CStack::Speed( int turn /*= 0*/ ) const
  643. {
  644. if(hasBonus(Selector::type(Bonus::SIEGE_WEAPON) && Selector::turns(turn))) //war machines cannot move
  645. return 0;
  646. int speed = valOfBonuses(Selector::type(Bonus::STACKS_SPEED) && Selector::turns(turn));
  647. int percentBonus = 0;
  648. BOOST_FOREACH(const Bonus &b, bonuses)
  649. {
  650. if(b.type == Bonus::STACKS_SPEED)
  651. {
  652. percentBonus += b.additionalInfo;
  653. }
  654. }
  655. speed = ((100 + percentBonus) * speed)/100;
  656. //bind effect check
  657. if(getEffect(72))
  658. {
  659. return 0;
  660. }
  661. return speed;
  662. }
  663. const CStack::StackEffect * CStack::getEffect( ui16 id, int turn /*= 0*/ ) const
  664. {
  665. for (unsigned int i=0; i< effects.size(); i++)
  666. if(effects[i].id == id)
  667. if(!turn || effects[i].turnsRemain > turn)
  668. return &effects[i];
  669. return NULL;
  670. }
  671. ui8 CStack::howManyEffectsSet(ui16 id) const
  672. {
  673. ui8 ret = 0;
  674. for (unsigned int i=0; i< effects.size(); i++)
  675. if(effects[i].id == id) //effect found
  676. {
  677. ++ret;
  678. }
  679. return ret;
  680. }
  681. bool CStack::willMove(int turn /*= 0*/) const
  682. {
  683. return ( turn ? true : !vstd::contains(state, DEFENDING) )
  684. && !moved(turn)
  685. && canMove(turn);
  686. }
  687. bool CStack::canMove( int turn /*= 0*/ ) const
  688. {
  689. return alive()
  690. && !hasBonus(Selector::type(Bonus::NOT_ACTIVE) && Selector::turns(turn)); //eg. Ammo Cart or blinded creature
  691. }
  692. bool CStack::moved( int turn /*= 0*/ ) const
  693. {
  694. if(!turn)
  695. return vstd::contains(state, MOVED);
  696. else
  697. return false;
  698. }
  699. bool CStack::doubleWide() const
  700. {
  701. return type->doubleWide;
  702. }
  703. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native, int player, const CTown *town, std::map<ui32,CGHeroInstance *> &available, const CHeroClass *bannedClass /*= NULL*/) const
  704. {
  705. CGHeroInstance *ret = NULL;
  706. if(player<0 || player>=PLAYER_LIMIT)
  707. {
  708. tlog1 << "Cannot pick hero for " << town->Name() << ". Wrong owner!\n";
  709. return NULL;
  710. }
  711. std::vector<CGHeroInstance *> pool;
  712. if(native)
  713. {
  714. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  715. {
  716. if(pavailable.find(i->first)->second & 1<<player
  717. && i->second->type->heroType/2 == town->typeID)
  718. {
  719. pool.push_back(i->second); //get all avaliable heroes
  720. }
  721. }
  722. if(!pool.size())
  723. {
  724. tlog1 << "Cannot pick native hero for " << player << ". Picking any...\n";
  725. return pickHeroFor(false, player, town, available);
  726. }
  727. else
  728. {
  729. ret = pool[rand()%pool.size()];
  730. }
  731. }
  732. else
  733. {
  734. int sum=0, r;
  735. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  736. {
  737. if(pavailable.find(i->first)->second & 1<<player
  738. && !bannedClass || i->second->type->heroClass != bannedClass)
  739. {
  740. pool.push_back(i->second);
  741. sum += i->second->type->heroClass->selectionProbability[town->typeID]; //total weight
  742. }
  743. }
  744. if(!pool.size())
  745. {
  746. tlog1 << "There are no heroes available for player " << player<<"!\n";
  747. return NULL;
  748. }
  749. r = rand()%sum;
  750. for (unsigned int i=0; i<pool.size(); i++)
  751. {
  752. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  753. if(r < 0)
  754. {
  755. ret = pool[i];
  756. break;
  757. }
  758. }
  759. if(!ret)
  760. ret = pool.back();
  761. }
  762. available.erase(ret->subID);
  763. return ret;
  764. }
  765. //void CGameState::apply(CPack * pack)
  766. //{
  767. // while(!mx->try_lock())
  768. // boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  769. // //applyNL(pack);
  770. // mx->unlock();
  771. //}
  772. int CGameState::pickHero(int owner)
  773. {
  774. int h=-1;
  775. if(!map->getHero(h = scenarioOps->getIthPlayersSettings(owner).hero,0) && h>=0) //we haven't used selected hero
  776. return h;
  777. int f = scenarioOps->getIthPlayersSettings(owner).castle;
  778. int i=0;
  779. do //try to find free hero of our faction
  780. {
  781. i++;
  782. h = scenarioOps->getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  783. } while( map->getHero(h) && i<175);
  784. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  785. {
  786. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  787. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  788. if(!map->getHero(j))
  789. h=j;
  790. }
  791. return h;
  792. }
  793. CGHeroInstance *CGameState::getHero(int objid)
  794. {
  795. if(objid<0 || objid>=map->objects.size() || map->objects[objid]->ID!=HEROI_TYPE)
  796. return NULL;
  797. return static_cast<CGHeroInstance *>(map->objects[objid]);
  798. }
  799. const CGHeroInstance * CGameState::getHero( int objid ) const
  800. {
  801. return (const_cast<CGameState *>(this))->getHero(objid);
  802. }
  803. CGTownInstance *CGameState::getTown(int objid)
  804. {
  805. if(objid<0 || objid>=map->objects.size())
  806. return NULL;
  807. return static_cast<CGTownInstance *>(map->objects[objid]);
  808. }
  809. const CGTownInstance * CGameState::getTown( int objid ) const
  810. {
  811. return (const_cast<CGameState *>(this))->getTown(objid);
  812. }
  813. std::pair<int,int> CGameState::pickObject (CGObjectInstance *obj)
  814. {
  815. switch(obj->ID)
  816. {
  817. case 65: //random artifact //how the hell use IGameCallback for this?
  818. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR | CArtifact::ART_RELIC));
  819. case 66: //random treasure artifact
  820. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_TREASURE));
  821. case 67: //random minor artifact
  822. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_MINOR));
  823. case 68: //random major artifact
  824. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_MAJOR));
  825. case 69: //random relic artifact
  826. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_RELIC));
  827. case 70: //random hero
  828. {
  829. return std::pair<int,int>(HEROI_TYPE,pickHero(obj->tempOwner));
  830. }
  831. case 71: //random monster
  832. {
  833. int r;
  834. do
  835. {
  836. r = ran()%197;
  837. } while (vstd::contains(VLC->creh->notUsedMonsters,r));
  838. return std::pair<int,int>(54,r);
  839. }
  840. case 72: //random monster lvl1
  841. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  842. case 73: //random monster lvl2
  843. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  844. case 74: //random monster lvl3
  845. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  846. case 75: //random monster lvl4
  847. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  848. case 76: //random resource
  849. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  850. case 77: //random town
  851. {
  852. int align = (static_cast<CGTownInstance*>(obj))->alignment,
  853. f;
  854. if(align>PLAYER_LIMIT-1)//same as owner / random
  855. {
  856. if(obj->tempOwner > PLAYER_LIMIT-1)
  857. f = -1; //random
  858. else
  859. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  860. }
  861. else
  862. {
  863. f = scenarioOps->getIthPlayersSettings(align).castle;
  864. }
  865. if(f<0) f = ran()%VLC->townh->towns.size();
  866. return std::pair<int,int>(TOWNI_TYPE,f);
  867. }
  868. case 162: //random monster lvl5
  869. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  870. case 163: //random monster lvl6
  871. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  872. case 164: //random monster lvl7
  873. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  874. case 216: //random dwelling
  875. {
  876. int faction = ran()%F_NUMBER;
  877. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  878. CCreGen2ObjInfo* info = static_cast<CCreGen2ObjInfo*>(dwl->info);
  879. if (info->asCastle)
  880. {
  881. for(unsigned int i=0;i<map->objects.size();i++)
  882. {
  883. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  884. {
  885. randomizeObject(map->objects[i]); //we have to randomize the castle first
  886. faction = map->objects[i]->subID;
  887. break;
  888. }
  889. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  890. {
  891. faction = map->objects[i]->subID;
  892. break;
  893. }
  894. }
  895. }
  896. else
  897. {
  898. while((!(info->castles[0]&(1<<faction))))
  899. {
  900. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  901. break;
  902. faction = ran()%F_NUMBER;
  903. }
  904. }
  905. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  906. int cid = VLC->townh->towns[faction].basicCreatures[level];
  907. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  908. if(VLC->objh->cregens[i]==cid)
  909. return std::pair<int,int>(17,i);
  910. tlog3 << "Cannot find a dwelling for creature "<< cid << std::endl;
  911. return std::pair<int,int>(17,0);
  912. delete dwl->info;
  913. dwl->info = NULL;
  914. }
  915. case 217:
  916. {
  917. int faction = ran()%F_NUMBER;
  918. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  919. CCreGenObjInfo* info = static_cast<CCreGenObjInfo*>(dwl->info);
  920. if (info->asCastle)
  921. {
  922. for(unsigned int i=0;i<map->objects.size();i++)
  923. {
  924. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  925. {
  926. randomizeObject(map->objects[i]); //we have to randomize the castle first
  927. faction = map->objects[i]->subID;
  928. break;
  929. }
  930. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  931. {
  932. faction = map->objects[i]->subID;
  933. break;
  934. }
  935. }
  936. }
  937. else
  938. {
  939. while((!(info->castles[0]&(1<<faction))))
  940. {
  941. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  942. break;
  943. faction = ran()%F_NUMBER;
  944. }
  945. }
  946. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  947. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  948. if(VLC->objh->cregens[i]==cid)
  949. return std::pair<int,int>(17,i);
  950. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  951. return std::pair<int,int>(17,0);
  952. delete dwl->info;
  953. dwl->info = NULL;
  954. }
  955. case 218:
  956. {
  957. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  958. CCreGen3ObjInfo* info = static_cast<CCreGen3ObjInfo*>(dwl->info);
  959. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  960. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  961. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  962. if(VLC->objh->cregens[i]==cid)
  963. return std::pair<int,int>(17,i);
  964. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  965. return std::pair<int,int>(17,0);
  966. delete dwl->info;
  967. dwl->info = NULL;
  968. }
  969. }
  970. return std::pair<int,int>(-1,-1);
  971. }
  972. void CGameState::randomizeObject(CGObjectInstance *cur)
  973. {
  974. std::pair<int,int> ran = pickObject(cur);
  975. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  976. {
  977. if(cur->ID==TOWNI_TYPE) //town - set def
  978. {
  979. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  980. t->town = &VLC->townh->towns[t->subID];
  981. if(t->hasCapitol())
  982. t->defInfo = capitols[t->subID];
  983. else if(t->hasFort())
  984. t->defInfo = forts[t->subID];
  985. else
  986. t->defInfo = villages[t->subID];
  987. }
  988. return;
  989. }
  990. else if(ran.first==HEROI_TYPE)//special code for hero
  991. {
  992. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  993. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  994. cur->ID = ran.first;
  995. h->portrait = cur->subID = ran.second;
  996. h->type = VLC->heroh->heroes[ran.second];
  997. h->randomizeArmy(h->type->heroType/2);
  998. map->heroes.push_back(h);
  999. return; //TODO: maybe we should do something with definfo?
  1000. }
  1001. else if(ran.first==TOWNI_TYPE)//special code for town
  1002. {
  1003. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  1004. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  1005. cur->ID = ran.first;
  1006. cur->subID = ran.second;
  1007. t->town = &VLC->townh->towns[ran.second];
  1008. if(t->hasCapitol())
  1009. t->defInfo = capitols[t->subID];
  1010. else if(t->hasFort())
  1011. t->defInfo = forts[t->subID];
  1012. else
  1013. t->defInfo = villages[t->subID];
  1014. t->randomizeArmy(t->subID);
  1015. map->towns.push_back(t);
  1016. return;
  1017. }
  1018. //we have to replace normal random object
  1019. cur->ID = ran.first;
  1020. cur->subID = ran.second;
  1021. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  1022. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  1023. if(!cur->defInfo)
  1024. {
  1025. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  1026. return;
  1027. }
  1028. map->addBlockVisTiles(cur);
  1029. }
  1030. int CGameState::getDate(int mode) const
  1031. {
  1032. int temp;
  1033. switch (mode)
  1034. {
  1035. case 0: //day number
  1036. return day;
  1037. break;
  1038. case 1: //day of week
  1039. temp = (day)%7;
  1040. if (temp)
  1041. return temp;
  1042. else return 7;
  1043. break;
  1044. case 2: //current week
  1045. temp = ((day-1)/7)+1;
  1046. if (!(temp%4))
  1047. return 4;
  1048. else
  1049. return (temp%4);
  1050. break;
  1051. case 3: //current month
  1052. return ((day-1)/28)+1;
  1053. break;
  1054. }
  1055. return 0;
  1056. }
  1057. CGameState::CGameState()
  1058. {
  1059. mx = new boost::shared_mutex();
  1060. map = NULL;
  1061. curB = NULL;
  1062. scenarioOps = NULL;
  1063. applierGs = new CGSApplier;
  1064. objCaller = new CObjectCallersHandler;
  1065. campaign = NULL;
  1066. }
  1067. CGameState::~CGameState()
  1068. {
  1069. delete mx;
  1070. delete map;
  1071. delete curB;
  1072. //delete scenarioOps;
  1073. delete applierGs;
  1074. delete objCaller;
  1075. }
  1076. void CGameState::init( StartInfo * si, ui32 checksum, int Seed )
  1077. {
  1078. switch(si->mode)
  1079. {
  1080. case 0:
  1081. map = new Mapa(si->mapname);
  1082. for (int i=0; i<144; ++i) //yes, 144
  1083. {
  1084. if (map->allowedArtifact[i])
  1085. VLC->arth->allowedArtifacts.push_back(VLC->arth->artifacts[i]);
  1086. }
  1087. break;
  1088. case 2:
  1089. campaign = new CCampaignState();
  1090. campaign->initNewCampaign(*si);
  1091. std::string &mapContent = campaign->camp->mapPieces[si->whichMapInCampaign];
  1092. map = new Mapa();
  1093. map->initFromBytes((const unsigned char*)mapContent.c_str());
  1094. for (int i=0; i<144; ++i)
  1095. {
  1096. if (map->allowedArtifact[i])
  1097. VLC->arth->allowedArtifacts.push_back(VLC->arth->artifacts[i]);
  1098. }
  1099. break;
  1100. }
  1101. tlog0 << "Map loaded!" << std::endl;
  1102. //tlog0 <<"Reading and detecting map file (together): "<<tmh.getDif()<<std::endl;
  1103. if(checksum)
  1104. {
  1105. tlog0 << "\tServer checksum for " << si->mapname <<": "<< checksum << std::endl;
  1106. tlog0 << "\tOur checksum for the map: "<< map->checksum << std::endl;
  1107. if(map->checksum != checksum)
  1108. {
  1109. tlog1 << "Wrong map checksum!!!" << std::endl;
  1110. throw std::string("Wrong checksum");
  1111. }
  1112. }
  1113. day = 0;
  1114. seed = Seed;
  1115. ran.seed((boost::int32_t)seed);
  1116. scenarioOps = si;
  1117. loadTownDInfos();
  1118. //pick grail location
  1119. if(map->grailPos.x < 0 || map->grailRadious) //grail not set or set within a radius around some place
  1120. {
  1121. if(!map->grailRadious) //radius not given -> anywhere on map
  1122. map->grailRadious = map->width * 2;
  1123. std::vector<int3> allowedPos;
  1124. // add all not blocked tiles in range
  1125. for (int i = 0; i < map->width ; i++)
  1126. {
  1127. for (int j = 0; j < map->height ; j++)
  1128. {
  1129. for (int k = 0; k <= map->twoLevel ; k++)
  1130. {
  1131. const TerrainTile &t = map->terrain[i][j][k];
  1132. if(!t.blocked
  1133. && !t.visitable
  1134. && t.tertype != TerrainTile::water
  1135. && t.tertype != TerrainTile::rock
  1136. && map->grailPos.dist2d(int3(i,j,k)) <= map->grailRadious)
  1137. allowedPos.push_back(int3(i,j,k));
  1138. }
  1139. }
  1140. }
  1141. //remove tiles with holes
  1142. for(unsigned int no=0; no<map->objects.size(); ++no)
  1143. if(map->objects[no]->ID == 124)
  1144. allowedPos -= map->objects[no]->pos;
  1145. if(allowedPos.size())
  1146. map->grailPos = allowedPos[ran() % allowedPos.size()];
  1147. else
  1148. tlog2 << "Warning: Grail cannot be placed, no appropriate tile found!\n";
  1149. }
  1150. //picking random factions for players
  1151. for(unsigned int i=0;i<scenarioOps->playerInfos.size();i++)
  1152. {
  1153. if(scenarioOps->playerInfos[i].castle==-1)
  1154. {
  1155. int f;
  1156. do
  1157. {
  1158. f = ran()%F_NUMBER;
  1159. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  1160. scenarioOps->playerInfos[i].castle = f;
  1161. }
  1162. }
  1163. //randomizing objects
  1164. for(unsigned int no=0; no<map->objects.size(); ++no)
  1165. {
  1166. randomizeObject(map->objects[no]);
  1167. if(map->objects[no]->ID==EVENTI_TYPE)
  1168. {
  1169. map->objects[no]->defInfo->handler=NULL;
  1170. }
  1171. map->objects[no]->hoverName = VLC->generaltexth->names[map->objects[no]->ID];
  1172. }
  1173. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  1174. /*********give starting hero****************************************/
  1175. for(int i=0;i<PLAYER_LIMIT;i++)
  1176. {
  1177. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==CMapHeader::RoE))
  1178. {
  1179. int3 hpos = map->players[i].posOfMainTown;
  1180. hpos.x+=1;// hpos.y+=1;
  1181. int j;
  1182. for(j=0; j<scenarioOps->playerInfos.size(); j++) //don't add unsigned here - we are refering to the variable above
  1183. if(scenarioOps->playerInfos[j].color == i)
  1184. break;
  1185. if(j == scenarioOps->playerInfos.size())
  1186. continue;
  1187. int h=pickHero(i);
  1188. if(scenarioOps->playerInfos[j].hero == -1)
  1189. scenarioOps->playerInfos[j].hero = h;
  1190. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(HEROI_TYPE,h,hpos,i));
  1191. nnn->id = map->objects.size();
  1192. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  1193. for(unsigned int o=0;o<map->towns.size();o++) //find main town
  1194. {
  1195. if(map->towns[o]->pos == hpos)
  1196. {
  1197. map->towns[o]->visitingHero = nnn;
  1198. nnn->visitedTown = map->towns[o];
  1199. nnn->inTownGarrison = false;
  1200. break;
  1201. }
  1202. }
  1203. nnn->initHero();
  1204. map->heroes.push_back(nnn);
  1205. map->objects.push_back(nnn);
  1206. map->addBlockVisTiles(nnn);
  1207. }
  1208. }
  1209. /*********creating players entries in gs****************************************/
  1210. for (unsigned int i=0; i<scenarioOps->playerInfos.size();i++)
  1211. {
  1212. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  1213. ins.second.color=ins.first;
  1214. ins.second.serial=i;
  1215. ins.second.human = scenarioOps->playerInfos[i].human;
  1216. players.insert(ins);
  1217. }
  1218. /******************RESOURCES****************************************************/
  1219. //TODO: computer player should receive other amount of resource than player (depending on difficulty)
  1220. std::vector<int> startres;
  1221. std::ifstream tis(DATA_DIR "/config/startres.txt");
  1222. int k;
  1223. for (int j=0;j<scenarioOps->difficulty;j++)
  1224. {
  1225. tis >> k;
  1226. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1227. tis>>k;
  1228. }
  1229. tis >> k;
  1230. for (int i=0;i<RESOURCE_QUANTITY;i++)
  1231. {
  1232. tis >> k;
  1233. startres.push_back(k);
  1234. }
  1235. tis.close();
  1236. tis.clear();
  1237. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1238. {
  1239. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1240. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1241. (*i).second.resources[x] = startres[x];
  1242. }
  1243. /*************************HEROES************************************************/
  1244. std::set<int> hids; //hero ids to create pool
  1245. for(unsigned int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1246. if(map->allowedHeroes[i])
  1247. hids.insert(i);
  1248. for (unsigned int i=0; i<map->heroes.size();i++) //heroes instances initialization
  1249. {
  1250. if (map->heroes[i]->getOwner()<0)
  1251. {
  1252. tlog2 << "Warning - hero with uninitialized owner!\n";
  1253. continue;
  1254. }
  1255. CGHeroInstance * vhi = (map->heroes[i]);
  1256. vhi->initHero();
  1257. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1258. hids.erase(vhi->subID);
  1259. }
  1260. for (unsigned int i=0; i<map->objects.size();i++) //prisons
  1261. {
  1262. if (map->objects[i]->ID == 62)
  1263. hids.erase(map->objects[i]->subID);
  1264. }
  1265. for(unsigned int i=0; i<map->predefinedHeroes.size(); i++)
  1266. {
  1267. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1268. continue;
  1269. map->predefinedHeroes[i]->initHero();
  1270. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1271. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1272. hids.erase(map->predefinedHeroes[i]->subID);
  1273. }
  1274. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go with default state into the pool
  1275. {
  1276. CGHeroInstance * vhi = new CGHeroInstance();
  1277. vhi->initHero(hid);
  1278. hpool.heroesPool[hid] = vhi;
  1279. hpool.pavailable[hid] = 0xff;
  1280. }
  1281. for(unsigned int i=0; i<map->disposedHeroes.size(); i++)
  1282. {
  1283. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1284. }
  1285. /*************************FOG**OF**WAR******************************************/
  1286. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1287. {
  1288. k->second.fogOfWarMap.resize(map->width);
  1289. for(int g=0; g<map->width; ++g)
  1290. k->second.fogOfWarMap[g].resize(map->height);
  1291. for(int g=-0; g<map->width; ++g)
  1292. for(int h=0; h<map->height; ++h)
  1293. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1294. for(int g=0; g<map->width; ++g)
  1295. for(int h=0; h<map->height; ++h)
  1296. for(int v=0; v<map->twoLevel+1; ++v)
  1297. k->second.fogOfWarMap[g][h][v] = 0;
  1298. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1299. {
  1300. if(obj->tempOwner != k->first) continue; //not a flagged object
  1301. std::set<int3> tiles;
  1302. obj->getSightTiles(tiles);
  1303. BOOST_FOREACH(int3 tile, tiles)
  1304. {
  1305. k->second.fogOfWarMap[tile.x][tile.y][tile.z] = 1;
  1306. }
  1307. }
  1308. //starting bonus
  1309. if(si->playerInfos[k->second.serial].bonus==brandom)
  1310. si->playerInfos[k->second.serial].bonus = ran()%3;
  1311. switch(si->playerInfos[k->second.serial].bonus)
  1312. {
  1313. case bgold:
  1314. k->second.resources[6] += 500 + (ran()%6)*100;
  1315. break;
  1316. case bresource:
  1317. {
  1318. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1319. if(res == 127)
  1320. {
  1321. k->second.resources[0] += 5 + ran()%6;
  1322. k->second.resources[2] += 5 + ran()%6;
  1323. }
  1324. else
  1325. {
  1326. k->second.resources[res] += 3 + ran()%4;
  1327. }
  1328. break;
  1329. }
  1330. case bartifact:
  1331. {
  1332. if(!k->second.heroes.size())
  1333. {
  1334. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1335. break;
  1336. }
  1337. CArtifact *toGive;
  1338. toGive = VLC->arth->artifacts[VLC->arth->getRandomArt (CArtifact::ART_TREASURE)];
  1339. CGHeroInstance *hero = k->second.heroes[0];
  1340. std::vector<ui16>::iterator slot = vstd::findFirstNot (hero->artifWorn, toGive->possibleSlots);
  1341. if(slot!=toGive->possibleSlots.end())
  1342. {
  1343. VLC->arth->equipArtifact(hero->artifWorn, *slot, toGive->id, &hero->bonuses);
  1344. }
  1345. else
  1346. hero->giveArtifact(toGive->id);
  1347. }
  1348. }
  1349. }
  1350. /****************************TOWNS************************************************/
  1351. for (unsigned int i=0;i<map->towns.size();i++)
  1352. {
  1353. CGTownInstance * vti =(map->towns[i]);
  1354. if(!vti->town)
  1355. vti->town = &VLC->townh->towns[vti->subID];
  1356. if (vti->name.length()==0) // if town hasn't name we draw it
  1357. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1358. //init buildings
  1359. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1360. {
  1361. vti->builtBuildings.erase(-50);
  1362. vti->builtBuildings.insert(10);
  1363. vti->builtBuildings.insert(5);
  1364. vti->builtBuildings.insert(30);
  1365. if(ran()%2)
  1366. vti->builtBuildings.insert(31);
  1367. }
  1368. if (vstd::contains(vti->builtBuildings,(6)) && vti->state()==3)
  1369. vti->builtBuildings.erase(6);//if we have harbor without water - erase it (this is H3 behaviour)
  1370. //init hordes
  1371. for (int i = 0; i<CREATURES_PER_TOWN; i++)
  1372. if (vstd::contains(vti->builtBuildings,(-31-i))) //if we have horde for this level
  1373. {
  1374. vti->builtBuildings.erase(-31-i);//remove old ID
  1375. if (vti->town->hordeLvl[0] == i)//if town first horde is this one
  1376. {
  1377. vti->builtBuildings.insert(18);//add it
  1378. if (vstd::contains(vti->builtBuildings,(37+i)))//if we have upgraded dwelling as well
  1379. vti->builtBuildings.insert(19);//add it as well
  1380. }
  1381. if (vti->town->hordeLvl[1] == i)//if town second horde is this one
  1382. {
  1383. vti->builtBuildings.insert(24);
  1384. if (vstd::contains(vti->builtBuildings,(37+i)))
  1385. vti->builtBuildings.insert(25);
  1386. }
  1387. }
  1388. //init spells
  1389. vti->spells.resize(SPELL_LEVELS);
  1390. CSpell *s;
  1391. for(unsigned int z=0; z<vti->obligatorySpells.size();z++)
  1392. {
  1393. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1394. vti->spells[s->level-1].push_back(s->id);
  1395. vti->possibleSpells -= s->id;
  1396. }
  1397. while(vti->possibleSpells.size())
  1398. {
  1399. ui32 total=0, sel=-1;
  1400. for(unsigned int ps=0;ps<vti->possibleSpells.size();ps++)
  1401. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1402. int r = (total)? ran()%total : -1;
  1403. for(unsigned int ps=0; ps<vti->possibleSpells.size();ps++)
  1404. {
  1405. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1406. if(r<0)
  1407. {
  1408. sel = ps;
  1409. break;
  1410. }
  1411. }
  1412. if(sel<0)
  1413. sel=0;
  1414. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1415. vti->spells[s->level-1].push_back(s->id);
  1416. vti->possibleSpells -= s->id;
  1417. }
  1418. if(vti->getOwner() != 255)
  1419. getPlayer(vti->getOwner())->towns.push_back(vti);
  1420. }
  1421. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1422. {
  1423. if(k->first==-1 || k->first==255)
  1424. continue;
  1425. //init visiting and garrisoned heroes
  1426. for(unsigned int l=0; l<k->second.heroes.size();l++)
  1427. {
  1428. CGHeroInstance *h = k->second.heroes[l];
  1429. for(unsigned int m=0; m<k->second.towns.size();m++)
  1430. {
  1431. CGTownInstance *t = k->second.towns[m];
  1432. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1433. if(vistile == h->pos || h->pos==t->pos)
  1434. {
  1435. t->visitingHero = h;
  1436. h->visitedTown = t;
  1437. h->inTownGarrison = false;
  1438. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1439. {
  1440. map->removeBlockVisTiles(h);
  1441. h->pos.x -= 1;
  1442. map->addBlockVisTiles(h);
  1443. }
  1444. break;
  1445. }
  1446. }
  1447. }
  1448. }
  1449. for(unsigned int i=0; i<map->defy.size(); i++)
  1450. {
  1451. map->defy[i]->serial = i;
  1452. }
  1453. objCaller->preInit();
  1454. for(unsigned int i=0; i<map->objects.size(); i++)
  1455. {
  1456. map->objects[i]->initObj();
  1457. if(map->objects[i]->ID == 62) //prison also needs to initialize hero
  1458. static_cast<CGHeroInstance*>(map->objects[i])->initHero();
  1459. }
  1460. objCaller->postInit();
  1461. }
  1462. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1463. {
  1464. return true;
  1465. }
  1466. bool CGameState::battleCanFlee(int player)
  1467. {
  1468. if(!curB) //there is no battle
  1469. return false;
  1470. if(curB->heroes[0]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE) //eg. one of heroes is wearing shakles of war
  1471. || curB->heroes[0]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE))
  1472. return false;
  1473. return true;
  1474. }
  1475. int CGameState::battleGetStack(int pos, bool onlyAlive)
  1476. {
  1477. if(!curB)
  1478. return -1;
  1479. for(unsigned int g=0; g<curB->stacks.size(); ++g)
  1480. {
  1481. if((curB->stacks[g]->position == pos
  1482. || (curB->stacks[g]->doubleWide()
  1483. &&( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos)
  1484. || (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos) )
  1485. ))
  1486. && (!onlyAlive || curB->stacks[g]->alive())
  1487. )
  1488. return curB->stacks[g]->ID;
  1489. }
  1490. return -1;
  1491. }
  1492. int CGameState::battleGetBattlefieldType(int3 tile)
  1493. {
  1494. if(tile==int3() && curB)
  1495. tile = curB->tile;
  1496. else if(tile==int3() && !curB)
  1497. return -1;
  1498. const std::vector <CGObjectInstance*> & objs = map->objects;
  1499. for(int g=0; g<objs.size(); ++g)
  1500. {
  1501. if( !objs[g] || objs[g]->pos.x - tile.x < 0 || objs[g]->pos.x - tile.x >= 8
  1502. || tile.y - objs[g]->pos.y + 5 < 0 || tile.y - objs[g]->pos.y + 5 >=6
  1503. || !objs[g]->coveringAt(objs[g]->pos.x - tile.x, tile.y - objs[g]->pos.y + 5)
  1504. ) //look only for objects covering given tile
  1505. continue;
  1506. switch(objs[g]->ID)
  1507. {
  1508. case 222: //clover field
  1509. return 19;
  1510. case 21: case 223: //cursed ground
  1511. return 22;
  1512. case 224: //evil fog
  1513. return 20;
  1514. case 225: //favourable winds
  1515. return 21;
  1516. case 226: //fiery fields
  1517. return 14;
  1518. case 227: //holy ground
  1519. return 18;
  1520. case 228: //lucid pools
  1521. return 17;
  1522. case 229: //magic clouds
  1523. return 16;
  1524. case 46: case 230: //magic plains
  1525. return 9;
  1526. case 231: //rocklands
  1527. return 15;
  1528. }
  1529. }
  1530. switch(map->terrain[tile.x][tile.y][tile.z].tertype)
  1531. {
  1532. case TerrainTile::dirt:
  1533. return rand()%3+3;
  1534. case TerrainTile::sand:
  1535. return 2; //TODO: coast support
  1536. case TerrainTile::grass:
  1537. return rand()%2+6;
  1538. case TerrainTile::snow:
  1539. return rand()%2+10;
  1540. case TerrainTile::swamp:
  1541. return 13;
  1542. case TerrainTile::rough:
  1543. return 23;
  1544. case TerrainTile::subterranean:
  1545. return 12;
  1546. case TerrainTile::lava:
  1547. return 8;
  1548. case TerrainTile::water:
  1549. return 25;
  1550. case TerrainTile::rock:
  1551. return 15;
  1552. default:
  1553. return -1;
  1554. }
  1555. }
  1556. const CGHeroInstance * CGameState::battleGetOwner(int stackID)
  1557. {
  1558. if(!curB)
  1559. return NULL;
  1560. return curB->heroes[!curB->getStack(stackID)->attackerOwned];
  1561. }
  1562. UpgradeInfo CGameState::getUpgradeInfo(const CArmedInstance *obj, int stackPos)
  1563. {
  1564. UpgradeInfo ret;
  1565. const CCreature *base = obj->getCreature(stackPos);
  1566. if((obj->ID == TOWNI_TYPE) || ((obj->ID == HEROI_TYPE) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
  1567. {
  1568. const CGTownInstance * t;
  1569. if(obj->ID == TOWNI_TYPE)
  1570. t = static_cast<const CGTownInstance *>(obj);
  1571. else
  1572. t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
  1573. for(std::set<si32>::const_iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++)
  1574. {
  1575. if( (*i) >= 37 && (*i) < 44 ) //upgraded creature dwelling
  1576. {
  1577. int nid = t->town->upgradedCreatures[(*i)-37]; //upgrade offered by that building
  1578. if(base->upgrades.find(nid) != base->upgrades.end()) //possible upgrade
  1579. {
  1580. ret.newID.push_back(nid);
  1581. ret.cost.push_back(std::set<std::pair<int,int> >());
  1582. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1583. {
  1584. int dif = VLC->creh->creatures[nid]->cost[j] - base->cost[j];
  1585. if(dif)
  1586. ret.cost[ret.cost.size()-1].insert(std::make_pair(j,dif));
  1587. }
  1588. }
  1589. }
  1590. }//end for
  1591. }
  1592. //TODO: check if hero ability makes some upgrades possible
  1593. if(ret.newID.size())
  1594. ret.oldID = base->idNumber;
  1595. return ret;
  1596. }
  1597. void CGameState::loadTownDInfos()
  1598. {
  1599. for(int i=0;i<F_NUMBER;i++)
  1600. {
  1601. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1602. forts[i] = VLC->dobjinfo->castles[i];
  1603. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1604. }
  1605. }
  1606. void CGameState::getNeighbours( const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand )
  1607. {
  1608. static int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1609. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1610. vec.clear();
  1611. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1612. {
  1613. const int3 hlp = tile + dirs[i];
  1614. if(!map->isInTheMap(hlp))
  1615. continue;
  1616. const TerrainTile &hlpt = map->getTile(hlp);
  1617. //we cannot visit things from blocked tiles
  1618. if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  1619. {
  1620. continue;
  1621. }
  1622. if((indeterminate(onLand) || onLand == (hlpt.tertype!=TerrainTile::water) )
  1623. && hlpt.tertype != TerrainTile::rock)
  1624. {
  1625. vec.push_back(hlp);
  1626. }
  1627. }
  1628. }
  1629. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  1630. {
  1631. if(src == dest) //same tile
  1632. return 0;
  1633. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1634. &d = map->terrain[dest.x][dest.y][dest.z];
  1635. //get basic cost
  1636. int ret = h->getTileCost(d,s);
  1637. if(d.blocked && h->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  1638. {
  1639. bool freeFlying = h->getBonusesCount(Selector::typeSybtype(Bonus::FLYING_MOVEMENT, 1)) > 0;
  1640. if(!freeFlying)
  1641. {
  1642. ret *= 1.4f; //40% penalty for movement over blocked tile
  1643. }
  1644. }
  1645. else if (d.tertype == TerrainTile::water)
  1646. {
  1647. if (!h->boat && h->getBonusesCount(Selector::typeSybtype(Bonus::WATER_WALKING, 1)) > 0)
  1648. {
  1649. ret *= 1.4f; //40% penalty for water walking
  1650. }
  1651. }
  1652. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1653. {
  1654. int old = ret;
  1655. ret *= 1.414213;
  1656. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1657. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1658. {
  1659. return remainingMovePoints;
  1660. }
  1661. }
  1662. int left = remainingMovePoints-ret;
  1663. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1664. {
  1665. std::vector<int3> vec;
  1666. getNeighbours(d, dest, vec, s.tertype != TerrainTile::water);
  1667. for(size_t i=0; i < vec.size(); i++)
  1668. {
  1669. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1670. if(fcost <= left)
  1671. {
  1672. return ret;
  1673. }
  1674. }
  1675. ret = remainingMovePoints;
  1676. }
  1677. return ret;
  1678. }
  1679. std::set<int> CGameState::getBuildingRequiments(const CGTownInstance *t, int ID)
  1680. {
  1681. std::set<int> used;
  1682. used.insert(ID);
  1683. std::set<int> reqs = VLC->townh->requirements[t->subID][ID];
  1684. while(true)
  1685. {
  1686. size_t noloop=0;
  1687. for(std::set<int>::iterator i=reqs.begin();i!=reqs.end();i++)
  1688. {
  1689. if(used.find(*i)==used.end()) //we haven't added requirements for this building
  1690. {
  1691. used.insert(*i);
  1692. for(
  1693. std::set<int>::iterator j=VLC->townh->requirements[t->subID][*i].begin();
  1694. j!=VLC->townh->requirements[t->subID][*i].end();
  1695. j++)
  1696. {
  1697. reqs.insert(*j);//creating full list of requirements
  1698. }
  1699. }
  1700. else
  1701. {
  1702. noloop++;
  1703. }
  1704. }
  1705. if(noloop==reqs.size())
  1706. break;
  1707. }
  1708. return reqs;
  1709. }
  1710. int CGameState::canBuildStructure( const CGTownInstance *t, int ID )
  1711. {
  1712. int ret = 7; //allowed by default
  1713. if(t->builded >= MAX_BUILDING_PER_TURN)
  1714. ret = 5; //building limit
  1715. //checking resources
  1716. CBuilding * pom = VLC->buildh->buildings[t->subID][ID];
  1717. if(!pom)
  1718. return 8;
  1719. // if(pom->Name().size()==0||pom->resources.size()==0)
  1720. // return 2;//TODO: why does this happen?
  1721. for(int res=0;res<pom->resources.size();res++) //TODO: support custom amount of resources
  1722. {
  1723. if(pom->resources[res] > getPlayer(t->tempOwner)->resources[res])
  1724. ret = 6; //lack of res
  1725. }
  1726. //checking for requirements
  1727. std::set<int> reqs = getBuildingRequiments(t, ID);//getting all requiments
  1728. for( std::set<int>::iterator ri = reqs.begin(); ri != reqs.end(); ri++ )
  1729. {
  1730. if(t->builtBuildings.find(*ri)==t->builtBuildings.end())
  1731. ret = 8; //lack of requirements - cannot build
  1732. }
  1733. //can we build it?
  1734. if(t->forbiddenBuildings.find(ID)!=t->forbiddenBuildings.end())
  1735. ret = 2; //forbidden
  1736. if(ID == 13) //capitol
  1737. {
  1738. for(unsigned int in = 0; in < map->towns.size(); in++)
  1739. {
  1740. if(map->towns[in]->tempOwner==t->tempOwner && vstd::contains(map->towns[in]->builtBuildings,13))
  1741. {
  1742. ret = 0; //no more than one capitol
  1743. break;
  1744. }
  1745. }
  1746. }
  1747. else if(ID == 6) //shipyard
  1748. {
  1749. int3 t1(t->pos + int3(-1,3,0)),
  1750. t2(t->pos + int3(-3,3,0));
  1751. if(map->isInTheMap(t1) && map->getTile(t1).tertype != TerrainTile::water
  1752. && (map->isInTheMap(t2) && map->getTile(t2).tertype != TerrainTile::water))
  1753. ret = 1; //lack of water
  1754. }
  1755. if(t->builtBuildings.find(ID)!=t->builtBuildings.end()) //already built
  1756. ret = 4;
  1757. return ret;
  1758. }
  1759. void CGameState::apply(CPack *pack)
  1760. {
  1761. ui16 typ = typeList.getTypeID(pack);
  1762. assert(typ >= 0);
  1763. applierGs->apps[typ]->applyOnGS(this,pack);
  1764. }
  1765. PlayerState * CGameState::getPlayer( ui8 color, bool verbose )
  1766. {
  1767. if(vstd::contains(players,color))
  1768. {
  1769. return &players[color];
  1770. }
  1771. else
  1772. {
  1773. if(verbose)
  1774. tlog2 << "Warning: Cannot find info for player " << int(color) << std::endl;
  1775. return NULL;
  1776. }
  1777. }
  1778. const PlayerState * CGameState::getPlayer( ui8 color, bool verbose ) const
  1779. {
  1780. return (const_cast<CGameState *>(this))->getPlayer(color, verbose);
  1781. }
  1782. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1783. {
  1784. if(!map->isInTheMap(src) || !map->isInTheMap(dest)) //check input
  1785. return false;
  1786. int3 hpos = hero->getPosition(false);
  1787. bool flying = false; //hero is under flying effect TODO
  1788. bool waterWalking = false; //hero is on land and can walk on water TODO
  1789. bool onLand = map->getTile(hpos).tertype != TerrainTile::water;
  1790. // tribool blockLandSea; //true - blocks sea, false - blocks land, indeterminate - allows all
  1791. //
  1792. // if (!hero->canWalkOnSea())
  1793. // blockLandSea = (map->getTile(hpos).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1794. // else
  1795. // blockLandSea = boost::logic::indeterminate;
  1796. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1797. //graph initialization
  1798. std::vector< std::vector<CPathNode> > graph;
  1799. graph.resize(map->width);
  1800. for(size_t i=0; i<graph.size(); ++i)
  1801. {
  1802. graph[i].resize(map->height);
  1803. for(size_t j=0; j<graph[i].size(); ++j)
  1804. {
  1805. const TerrainTile *tinfo = &map->terrain[i][j][src.z];
  1806. CPathNode &node = graph[i][j];
  1807. node.accessible = !tinfo->blocked;
  1808. node.dist = -1;
  1809. node.theNodeBefore = NULL;
  1810. node.visited = false;
  1811. node.coord.x = i;
  1812. node.coord.y = j;
  1813. node.coord.z = dest.z;
  1814. if(!tinfo->entrableTerrain(onLand, flying || waterWalking)
  1815. || !FoW[i][j][src.z] //tile is covered by the FoW
  1816. )
  1817. {
  1818. node.accessible = false;
  1819. }
  1820. }
  1821. }
  1822. //Special rules for the destination tile
  1823. {
  1824. const TerrainTile *t = &map->terrain[dest.x][dest.y][dest.z];
  1825. CPathNode &d = graph[dest.x][dest.y];
  1826. //tile may be blocked by blockvis / normal vis obj but it still must be accessible
  1827. if(t->visitable)
  1828. {
  1829. d.accessible = true; //for allowing visiting objects
  1830. }
  1831. if(onLand && t->tertype == TerrainTile::water) //hero can walk only on land and dst lays on the water
  1832. {
  1833. size_t i = 0;
  1834. for(; i < t->visitableObjects.size(); i++)
  1835. if(t->visitableObjects[i]->ID == 8 || t->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1836. break;
  1837. d.accessible = (i < t->visitableObjects.size()); //dest is accessible only if there is boat/hero
  1838. }
  1839. else if(!onLand && t->tertype != TerrainTile::water) //hero is moving by water
  1840. {
  1841. d.accessible = (t->siodmyTajemniczyBajt & 64) && !t->blocked; //tile is accessible if it's coastal and not blocked
  1842. }
  1843. }
  1844. //graph initialized
  1845. //initial tile - set cost on 0 and add to the queue
  1846. graph[src.x][src.y].dist = 0;
  1847. std::queue<CPathNode> mq;
  1848. mq.push(graph[src.x][src.y]);
  1849. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1850. std::vector<int3> neighbours;
  1851. neighbours.reserve(8);
  1852. while(!mq.empty())
  1853. {
  1854. CPathNode &cp = graph[mq.front().coord.x][mq.front().coord.y];
  1855. mq.pop();
  1856. if (cp.coord == dest) //it's destination tile
  1857. {
  1858. if (cp.dist < curDist) //that path is better than previous one
  1859. curDist = cp.dist;
  1860. continue;
  1861. }
  1862. else
  1863. {
  1864. if (cp.dist > curDist) //it's not dest and current length is greater than cost of already found path
  1865. continue;
  1866. }
  1867. //add accessible neighbouring nodes to the queue
  1868. getNeighbours(map->getTile(cp.coord), cp.coord, neighbours, boost::logic::indeterminate);
  1869. for(unsigned int i=0; i < neighbours.size(); i++)
  1870. {
  1871. CPathNode & dp = graph[neighbours[i].x][neighbours[i].y];
  1872. if(dp.accessible)
  1873. {
  1874. int cost = getMovementCost(hero,cp.coord,dp.coord,hero->movement - cp.dist);
  1875. if((dp.dist==-1 || (dp.dist > cp.dist + cost)) && dp.accessible && checkForVisitableDir(cp.coord, dp.coord) && checkForVisitableDir(dp.coord, cp.coord))
  1876. {
  1877. dp.dist = cp.dist + cost;
  1878. dp.theNodeBefore = &cp;
  1879. mq.push(dp);
  1880. }
  1881. }
  1882. }
  1883. }
  1884. CPathNode *curNode = &graph[dest.x][dest.y];
  1885. if(!curNode->theNodeBefore) //destination is not accessible
  1886. return false;
  1887. //fill ret with found path
  1888. ret.nodes.clear();
  1889. while(curNode->coord != graph[src.x][src.y].coord)
  1890. {
  1891. ret.nodes.push_back(*curNode);
  1892. curNode = curNode->theNodeBefore;
  1893. }
  1894. ret.nodes.push_back(graph[src.x][src.y]);
  1895. return true;
  1896. }
  1897. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  1898. {
  1899. assert(hero);
  1900. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1901. if(src.x < 0)
  1902. src = hero->getPosition(false);
  1903. if(movement < 0)
  1904. movement = hero->movement;
  1905. out.hero = hero;
  1906. out.hpos = src;
  1907. if(!map->isInTheMap(src)/* || !map->isInTheMap(dest)*/) //check input
  1908. {
  1909. tlog1 << "CGameState::calculatePaths: Hero outside the map? How dare you...\n";
  1910. return;
  1911. }
  1912. tribool onLand; //true - blocks sea, false - blocks land, indeterminate - allows all
  1913. if (!hero->canWalkOnSea())
  1914. onLand = (map->getTile(src).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1915. else
  1916. onLand = boost::logic::indeterminate;
  1917. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1918. bool flying = hero->hasBonusOfType(Bonus::FLYING_MOVEMENT);
  1919. bool waterWalk = hero->hasBonusOfType(Bonus::WATER_WALKING);
  1920. //graph initialization
  1921. CGPathNode ***graph = out.nodes;
  1922. for(size_t i=0; i < out.sizes.x; ++i)
  1923. {
  1924. for(size_t j=0; j < out.sizes.y; ++j)
  1925. {
  1926. for(size_t k=0; k < out.sizes.z; ++k)
  1927. {
  1928. const TerrainTile *tinfo = &map->terrain[i][j][k];
  1929. CGPathNode &node = graph[i][j][k];
  1930. node.accessible = (tinfo->blocked ? CGPathNode::FLYABLE : CGPathNode::ACCESSIBLE);
  1931. if(!flying && node.accessible == CGPathNode::FLYABLE)
  1932. {
  1933. node.accessible = CGPathNode::BLOCKED;
  1934. }
  1935. node.turns = 0xff;
  1936. node.moveRemains = 0;
  1937. node.coord.x = i;
  1938. node.coord.y = j;
  1939. node.coord.z = k;
  1940. node.land = tinfo->tertype != TerrainTile::water;
  1941. node.theNodeBefore = NULL;
  1942. if((onLand || indeterminate(onLand)) && !node.land)//it's sea and we cannot walk on sea
  1943. {
  1944. if (waterWalk || flying)
  1945. {
  1946. node.accessible = CGPathNode::FLYABLE;
  1947. }
  1948. else
  1949. {
  1950. node.accessible = CGPathNode::BLOCKED;
  1951. }
  1952. }
  1953. if ( tinfo->tertype == TerrainTile::rock//it's rock
  1954. || !onLand && node.land //it's land and we cannot walk on land (complementary condition is handled above)
  1955. || !FoW[i][j][k] //tile is covered by the FoW
  1956. )
  1957. {
  1958. node.accessible = CGPathNode::BLOCKED;
  1959. }
  1960. else if(tinfo->visitable)
  1961. {
  1962. for(size_t ii = 0; ii < tinfo->visitableObjects.size(); ii++)
  1963. {
  1964. const CGObjectInstance * const obj = tinfo->visitableObjects[ii];
  1965. if(obj->getPassableness() & 1<<hero->tempOwner) //special object instance specific passableness flag - overwrites other accessibility flags
  1966. {
  1967. node.accessible = CGPathNode::ACCESSIBLE;
  1968. }
  1969. else if(obj->blockVisit)
  1970. {
  1971. node.accessible = CGPathNode::BLOCKVIS;
  1972. break;
  1973. }
  1974. else if(obj->ID != EVENTI_TYPE) //pathfinder should ignore placed events
  1975. {
  1976. node.accessible = CGPathNode::VISITABLE;
  1977. }
  1978. }
  1979. }
  1980. else if (map->isInTheMap(guardingCreaturePosition(int3(i, j, k)))
  1981. && tinfo->blockingObjects.size() == 0)
  1982. {
  1983. // Monster close by; blocked visit for battle.
  1984. node.accessible = CGPathNode::BLOCKVIS;
  1985. }
  1986. if(onLand && !node.land) //hero can walk only on land and tile lays on the water
  1987. {
  1988. size_t i = 0;
  1989. for(; i < tinfo->visitableObjects.size(); i++)
  1990. if(tinfo->visitableObjects[i]->ID == 8 || tinfo->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1991. break;
  1992. if(i < tinfo->visitableObjects.size())
  1993. node.accessible = CGPathNode::BLOCKVIS; //dest is accessible only if there is boat/hero
  1994. }
  1995. else if(!onLand && tinfo->tertype != TerrainTile::water) //hero is moving by water
  1996. {
  1997. if((tinfo->siodmyTajemniczyBajt & 64) && !tinfo->blocked)
  1998. node.accessible = CGPathNode::VISITABLE; //tile is accessible if it's coastal and not blocked
  1999. }
  2000. }
  2001. }
  2002. }
  2003. //graph initialized
  2004. //initial tile - set cost on 0 and add to the queue
  2005. graph[src.x][src.y][src.z].turns = 0;
  2006. graph[src.x][src.y][src.z].moveRemains = movement;
  2007. std::queue<CGPathNode*> mq;
  2008. mq.push(&graph[src.x][src.y][src.z]);
  2009. //ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  2010. std::vector<int3> neighbours;
  2011. neighbours.reserve(8);
  2012. while(!mq.empty())
  2013. {
  2014. CGPathNode *cp = mq.front();
  2015. mq.pop();
  2016. const int3 guardPosition = guardingCreaturePosition(cp->coord);
  2017. const bool guardedPosition = (guardPosition != int3(-1, -1, -1) && cp->coord != src);
  2018. const TerrainTile &ct = map->getTile(cp->coord);
  2019. int movement = cp->moveRemains, turn = cp->turns;
  2020. if(!movement)
  2021. {
  2022. movement = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  2023. turn++;
  2024. }
  2025. //add accessible neighbouring nodes to the queue
  2026. getNeighbours(ct, cp->coord, neighbours, boost::logic::indeterminate);
  2027. for(unsigned int i=0; i < neighbours.size(); i++)
  2028. {
  2029. int moveAtNextTile = movement;
  2030. int turnAtNextTile = turn;
  2031. const int3 &n = neighbours[i]; //current neighbor
  2032. CGPathNode & dp = graph[n.x][n.y][n.z];
  2033. if( !checkForVisitableDir(cp->coord, dp.coord)
  2034. || !checkForVisitableDir(dp.coord, cp->coord)
  2035. || dp.accessible == CGPathNode::BLOCKED )
  2036. {
  2037. continue;
  2038. }
  2039. int cost = getMovementCost(hero, cp->coord, dp.coord, movement);
  2040. int remains = movement - cost;
  2041. if(remains < 0)
  2042. {
  2043. //occurs rarely, when hero with low movepoints tries to go leave the road
  2044. turnAtNextTile++;
  2045. moveAtNextTile = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  2046. cost = getMovementCost(hero, cp->coord, dp.coord, moveAtNextTile); //cost must be updated, movement points changed :(
  2047. remains = moveAtNextTile - cost;
  2048. }
  2049. const bool neighborIsGuard = guardingCreaturePosition(cp->coord) == dp.coord;
  2050. if((dp.turns==0xff //we haven't been here before
  2051. || dp.turns > turnAtNextTile
  2052. || (dp.turns >= turnAtNextTile && dp.moveRemains < remains)) //this route is faster
  2053. && (!guardedPosition || neighborIsGuard)) // Can step into tile of guard
  2054. {
  2055. assert(&dp != cp->theNodeBefore); //two tiles can't point to each other
  2056. dp.moveRemains = remains;
  2057. dp.turns = turnAtNextTile;
  2058. dp.theNodeBefore = cp;
  2059. const bool guardedNeighbor = guardingCreaturePosition(dp.coord) != int3(-1, -1, -1);
  2060. //const bool positionIsGuard = guardingCreaturePosition(cp->coord) == cp->coord; //can this be true? hero never passes from monster tile...
  2061. if (dp.accessible == CGPathNode::ACCESSIBLE || dp.accessible == CGPathNode::FLYABLE
  2062. || (guardedNeighbor && !guardedPosition)) // Can step into a hostile tile once.
  2063. {
  2064. mq.push(&dp);
  2065. }
  2066. }
  2067. } //neighbours loop
  2068. } //queue loop
  2069. }
  2070. /**
  2071. * Tells if the tile is guarded by a monster as well as the position
  2072. * of the monster that will attack on it.
  2073. *
  2074. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  2075. * the monster guarding the tile.
  2076. */
  2077. int3 CGameState::guardingCreaturePosition (int3 pos) const
  2078. {
  2079. const int3 originalPos = pos;
  2080. // Give monster at position priority.
  2081. if (!map->isInTheMap(pos))
  2082. return int3(-1, -1, -1);
  2083. const TerrainTile &posTile = map->terrain[pos.x][pos.y][pos.z];
  2084. if (posTile.visitable)
  2085. {
  2086. BOOST_FOREACH (CGObjectInstance* obj, posTile.visitableObjects)
  2087. {
  2088. if(obj->blockVisit)
  2089. {
  2090. if (obj->ID == 54) // Monster
  2091. return pos;
  2092. else
  2093. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  2094. }
  2095. }
  2096. }
  2097. // See if there are any monsters adjacent.
  2098. pos -= int3(1, 1, 0); // Start with top left.
  2099. for (int dx = 0; dx < 3; dx++)
  2100. {
  2101. for (int dy = 0; dy < 3; dy++)
  2102. {
  2103. if (map->isInTheMap(pos))
  2104. {
  2105. TerrainTile &tile = map->terrain[pos.x][pos.y][pos.z];
  2106. if (tile.visitable)
  2107. {
  2108. BOOST_FOREACH (CGObjectInstance* obj, tile.visitableObjects)
  2109. {
  2110. if (obj->ID == 54 && checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  2111. {
  2112. return pos;
  2113. }
  2114. }
  2115. }
  2116. }
  2117. pos.y++;
  2118. }
  2119. pos.y -= 3;
  2120. pos.x++;
  2121. }
  2122. return int3(-1, -1, -1);
  2123. }
  2124. bool CGameState::isVisible(int3 pos, int player)
  2125. {
  2126. if(player == 255) //neutral player
  2127. return false;
  2128. return players[player].fogOfWarMap[pos.x][pos.y][pos.z];
  2129. }
  2130. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  2131. {
  2132. if(player == 255) //neutral player
  2133. return false;
  2134. //object is visible when at least one blocked tile is visible
  2135. for(int fx=0; fx<8; ++fx)
  2136. {
  2137. for(int fy=0; fy<6; ++fy)
  2138. {
  2139. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  2140. if(map->isInTheMap(pos)
  2141. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  2142. && isVisible(pos, player) )
  2143. return true;
  2144. }
  2145. }
  2146. return false;
  2147. }
  2148. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  2149. {
  2150. const TerrainTile * pom = &map->getTile(dst);
  2151. return checkForVisitableDir(src, pom, dst);
  2152. }
  2153. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  2154. {
  2155. for(unsigned int b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  2156. {
  2157. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  2158. continue;
  2159. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  2160. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  2161. {
  2162. return false;
  2163. }
  2164. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  2165. {
  2166. return false;
  2167. }
  2168. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  2169. {
  2170. return false;
  2171. }
  2172. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  2173. {
  2174. return false;
  2175. }
  2176. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  2177. {
  2178. return false;
  2179. }
  2180. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  2181. {
  2182. return false;
  2183. }
  2184. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  2185. {
  2186. return false;
  2187. }
  2188. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  2189. {
  2190. return false;
  2191. }
  2192. }
  2193. return true;
  2194. }
  2195. std::pair<ui32, ui32> BattleInfo::calculateDmgRange( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky )
  2196. {
  2197. float additiveBonus=1.0f, multBonus=1.0f,
  2198. minDmg = attacker->type->damageMin * attacker->count,
  2199. maxDmg = attacker->type->damageMax * attacker->count;
  2200. if(attacker->type->idNumber == 149) //arrow turret
  2201. {
  2202. switch(attacker->position)
  2203. {
  2204. case -2: //keep
  2205. minDmg = 15;
  2206. maxDmg = 15;
  2207. break;
  2208. case -3: case -4: //turrets
  2209. minDmg = 7.5f;
  2210. maxDmg = 7.5f;
  2211. break;
  2212. }
  2213. }
  2214. if(attacker->hasBonusOfType(Bonus::SIEGE_WEAPON) && attacker->type->idNumber != 149) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  2215. { //minDmg and maxDmg are multiplied by hero attack + 1
  2216. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  2217. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  2218. }
  2219. int attackDefenceDifference = 0;
  2220. if(attacker->hasBonusOfType(Bonus::GENERAL_ATTACK_REDUCTION))
  2221. {
  2222. float multAttackReduction = attacker->valOfBonuses(Bonus::GENERAL_ATTACK_REDUCTION, -1024) / 100.0f;
  2223. attackDefenceDifference = attacker->Attack() * multAttackReduction;
  2224. }
  2225. else
  2226. {
  2227. attackDefenceDifference = attacker->Attack();
  2228. }
  2229. if(attacker->hasBonusOfType(Bonus::ENEMY_DEFENCE_REDUCTION))
  2230. {
  2231. float multDefenceReduction = (100.0f - attacker->valOfBonuses(Bonus::ENEMY_DEFENCE_REDUCTION, -1024)) / 100.0f;
  2232. attackDefenceDifference -= defender->Defense() * multDefenceReduction;
  2233. }
  2234. else
  2235. {
  2236. attackDefenceDifference -= defender->Defense();
  2237. }
  2238. //calculating total attack/defense skills modifier
  2239. if(shooting) //precision handling (etc.)
  2240. attackDefenceDifference += attacker->getBonuses(Selector::typeSybtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT)).totalValue();
  2241. else //bloodlust handling (etc.)
  2242. attackDefenceDifference += attacker->getBonuses(Selector::typeSybtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_MELEE_FIGHT)).totalValue();
  2243. if(attacker->getEffect(55)) //slayer handling
  2244. {
  2245. std::vector<int> affectedIds;
  2246. int spLevel = attacker->getEffect(55)->level;
  2247. for(int g = 0; g < VLC->creh->creatures.size(); ++g)
  2248. {
  2249. BOOST_FOREACH(const Bonus &b, VLC->creh->creatures[g]->bonuses)
  2250. {
  2251. if ( (b.type == Bonus::KING3 && spLevel >= 3) || //expert
  2252. (b.type == Bonus::KING2 && spLevel >= 2) || //adv +
  2253. (b.type == Bonus::KING1 && spLevel >= 0) ) //none or basic +
  2254. {
  2255. affectedIds.push_back(g);
  2256. break;
  2257. }
  2258. }
  2259. }
  2260. for(unsigned int g=0; g<affectedIds.size(); ++g)
  2261. {
  2262. if(defender->type->idNumber == affectedIds[g])
  2263. {
  2264. attackDefenceDifference += VLC->spellh->spells[55].powers[attacker->getEffect(55)->level];
  2265. break;
  2266. }
  2267. }
  2268. }
  2269. //bonus from attack/defense skills
  2270. if(attackDefenceDifference < 0) //decreasing dmg
  2271. {
  2272. float dec = 0.025f * (-attackDefenceDifference);
  2273. if(dec > 0.7f)
  2274. {
  2275. multBonus *= 0.3f; //1.0 - 0.7
  2276. }
  2277. else
  2278. {
  2279. multBonus *= 1.0f - dec;
  2280. }
  2281. }
  2282. else //increasing dmg
  2283. {
  2284. float inc = 0.05f * attackDefenceDifference;
  2285. if(inc > 4.0f)
  2286. {
  2287. additiveBonus += 4.0f;
  2288. }
  2289. else
  2290. {
  2291. additiveBonus += inc;
  2292. }
  2293. }
  2294. //applying jousting bonus
  2295. if( attacker->hasBonusOfType(Bonus::JOUSTING) && !defender->hasBonusOfType(Bonus::CHARGE_IMMUNITY) )
  2296. additiveBonus += charge * 0.05f;
  2297. //handling secondary abilities and artifacts giving premies to them
  2298. if(attackerHero)
  2299. {
  2300. if(shooting)
  2301. {
  2302. switch(attackerHero->getSecSkillLevel(1)) //archery
  2303. {
  2304. case 1: //basic
  2305. additiveBonus += 0.1f;
  2306. break;
  2307. case 2: //advanced
  2308. additiveBonus += 0.25f;
  2309. break;
  2310. case 3: //expert
  2311. additiveBonus += 0.5f;
  2312. break;
  2313. }
  2314. if(attackerHero->getSecSkillLevel(1) > 0) //non-none level
  2315. {
  2316. //apply artifact premy to archery
  2317. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 1) / 100.0f;
  2318. }
  2319. }
  2320. else
  2321. {
  2322. switch(attackerHero->getSecSkillLevel(22)) //offense
  2323. {
  2324. case 1: //basic
  2325. additiveBonus += 0.1f;
  2326. break;
  2327. case 2: //advanced
  2328. additiveBonus += 0.2f;
  2329. break;
  2330. case 3: //expert
  2331. additiveBonus += 0.3f;
  2332. break;
  2333. }
  2334. }
  2335. }
  2336. if(defendingHero)
  2337. {
  2338. switch(defendingHero->getSecSkillLevel(23)) //armorer
  2339. {
  2340. case 1: //basic
  2341. multBonus *= 0.95f;
  2342. break;
  2343. case 2: //advanced
  2344. multBonus *= 0.9f;
  2345. break;
  2346. case 3: //expert
  2347. multBonus *= 0.85f;
  2348. break;
  2349. }
  2350. }
  2351. //handling hate effect
  2352. if( attacker->hasBonusOfType(Bonus::HATE, defender->type->idNumber) )
  2353. additiveBonus += 0.5f;
  2354. //luck bonus
  2355. if (lucky)
  2356. {
  2357. additiveBonus += 1.0f;
  2358. }
  2359. //handling spell effects
  2360. if(!shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  2361. {
  2362. multBonus *= float(defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0f;
  2363. }
  2364. else if(shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  2365. {
  2366. multBonus *= float(defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0f;
  2367. }
  2368. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  2369. {
  2370. multBonus *= 0.8f * float(VLC->spellh->spells[42].powers[attacker->getEffect(42)->level]); //the second factor is 1 or 0
  2371. }
  2372. class HLP
  2373. {
  2374. public:
  2375. static bool hasAdvancedAirShield(const CStack * stack)
  2376. {
  2377. for(int g=0; g<stack->effects.size(); ++g)
  2378. {
  2379. if (stack->effects[g].id == 28 && stack->effects[g].level >= 2)
  2380. {
  2381. return true;
  2382. }
  2383. }
  2384. return false;
  2385. }
  2386. };
  2387. //wall / distance penalty + advanced air shield
  2388. if (shooting && !NBonus::hasOfType(attackerHero, Bonus::NO_SHOTING_PENALTY) && (
  2389. hasDistancePenalty(attacker->ID, defender->position) || hasWallPenalty(attacker->ID, defender->position) ||
  2390. HLP::hasAdvancedAirShield(defender) )
  2391. )
  2392. {
  2393. multBonus *= 0.5;
  2394. }
  2395. if (!shooting && attacker->hasBonusOfType(Bonus::SHOOTER) && !attacker->hasBonusOfType(Bonus::NO_MELEE_PENALTY))
  2396. {
  2397. multBonus *= 0.5;
  2398. }
  2399. minDmg *= additiveBonus * multBonus;
  2400. maxDmg *= additiveBonus * multBonus;
  2401. std::pair<ui32, ui32> returnedVal;
  2402. if(attacker->getEffect(42)) //curse handling (rest)
  2403. {
  2404. minDmg -= VLC->spellh->spells[42].powers[attacker->getEffect(42)->level];
  2405. returnedVal = std::make_pair(int(minDmg), int(minDmg));
  2406. }
  2407. else if(attacker->getEffect(41)) //bless handling
  2408. {
  2409. maxDmg += VLC->spellh->spells[41].powers[attacker->getEffect(41)->level];
  2410. returnedVal = std::make_pair(int(maxDmg), int(maxDmg));
  2411. }
  2412. else
  2413. {
  2414. returnedVal = std::make_pair(int(minDmg), int(maxDmg));
  2415. }
  2416. //damage cannot be less than 1
  2417. amax(returnedVal.first, 1);
  2418. amax(returnedVal.second, 1);
  2419. return returnedVal;
  2420. }
  2421. ui32 BattleInfo::calculateDmg( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky )
  2422. {
  2423. std::pair<ui32, ui32> range = calculateDmgRange(attacker, defender, attackerHero, defendingHero, shooting, charge, lucky);
  2424. if(range.first != range.second)
  2425. {
  2426. int valuesToAverage[10];
  2427. int howManyToAv = std::min<ui32>(10, attacker->count);
  2428. for (int g=0; g<howManyToAv; ++g)
  2429. {
  2430. valuesToAverage[g] = range.first + rand() % (range.second - range.first + 1);
  2431. }
  2432. return std::accumulate(valuesToAverage, valuesToAverage + howManyToAv, 0) / howManyToAv;
  2433. }
  2434. else
  2435. return range.first;
  2436. }
  2437. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  2438. {
  2439. for(unsigned int i=0; i<stacks.size();i++)//setting casualties
  2440. {
  2441. const CStack * const st = stacks[i];
  2442. si32 killed = (st->alive() ? st->baseAmount - st->count : st->baseAmount);
  2443. amax(killed, 0);
  2444. if(killed)
  2445. casualties[!st->attackerOwned][st->type->idNumber] += killed;
  2446. }
  2447. }
  2448. si8 CGameState::battleMaxSpellLevel()
  2449. {
  2450. if(!curB) //there is not battle
  2451. {
  2452. tlog1 << "si8 CGameState::maxSpellLevel() call when there is no battle!" << std::endl;
  2453. throw "si8 CGameState::maxSpellLevel() call when there is no battle!";
  2454. }
  2455. si8 levelLimit = SPELL_LEVELS;
  2456. const CGHeroInstance *h1 = curB->heroes[0];
  2457. if(h1)
  2458. {
  2459. for(std::list<Bonus>::const_iterator i = h1->bonuses.begin(); i != h1->bonuses.end(); i++)
  2460. if(i->type == Bonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2461. amin(levelLimit, i->val);
  2462. }
  2463. const CGHeroInstance *h2 = curB->heroes[1];
  2464. if(h2)
  2465. {
  2466. for(std::list<Bonus>::const_iterator i = h2->bonuses.begin(); i != h2->bonuses.end(); i++)
  2467. if(i->type == Bonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2468. amin(levelLimit, i->val);
  2469. }
  2470. return levelLimit;
  2471. }
  2472. std::set<CStack*> BattleInfo::getAttackedCreatures( const CSpell * s, int skillLevel, ui8 attackerOwner, int destinationTile )
  2473. {
  2474. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, skillLevel);
  2475. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
  2476. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  2477. if(s->id == 24 || s->id == 25 || s->id == 26) //death ripple, destroy undead and Armageddon
  2478. {
  2479. for(int it=0; it<stacks.size(); ++it)
  2480. {
  2481. if((s->id == 24 && !stacks[it]->type->isUndead()) //death ripple
  2482. || (s->id == 25 && stacks[it]->type->isUndead()) //destroy undead
  2483. || (s->id == 26) //Armageddon
  2484. )
  2485. {
  2486. if(stacks[it]->alive())
  2487. attackedCres.insert(stacks[it]);
  2488. }
  2489. }
  2490. }
  2491. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_1") != std::string::npos
  2492. || 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
  2493. {
  2494. if(skillLevel < 3) /*not expert */
  2495. {
  2496. CStack * st = getStackT(destinationTile, onlyAlive);
  2497. if(st)
  2498. attackedCres.insert(st);
  2499. }
  2500. else
  2501. {
  2502. for(int it=0; it<stacks.size(); ++it)
  2503. {
  2504. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  2505. if((VLC->spellh->spells[s->id].positiveness >= 0 && stacks[it]->owner == attackerOwner)
  2506. ||(VLC->spellh->spells[s->id].positiveness <= 0 && stacks[it]->owner != attackerOwner )
  2507. )
  2508. {
  2509. if(!onlyAlive || stacks[it]->alive())
  2510. attackedCres.insert(stacks[it]);
  2511. }
  2512. }
  2513. } //if(caster->getSpellSchoolLevel(s) < 3)
  2514. }
  2515. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET") != std::string::npos) //spell to be cast on one specific creature
  2516. {
  2517. CStack * st = getStackT(destinationTile, onlyAlive);
  2518. if(st)
  2519. attackedCres.insert(st);
  2520. }
  2521. else //custom range from attackedHexes
  2522. {
  2523. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  2524. {
  2525. CStack * st = getStackT(*it, onlyAlive);
  2526. if(st)
  2527. attackedCres.insert(st);
  2528. }
  2529. }
  2530. return attackedCres;
  2531. }
  2532. int BattleInfo::calculateSpellDuration( const CSpell * spell, const CGHeroInstance * caster, int usedSpellPower )
  2533. {
  2534. if(!caster) //TODO: something better
  2535. return std::max(5, usedSpellPower);
  2536. switch(spell->id)
  2537. {
  2538. case 56: //frenzy
  2539. return 1;
  2540. default: //other spells
  2541. return caster->getPrimSkillLevel(2) + caster->valOfBonuses(Bonus::SPELL_DURATION);
  2542. }
  2543. }
  2544. CStack * BattleInfo::generateNewStack(const CStackInstance &base, int stackID, bool attackerOwned, int slot, int /*TerrainTile::EterrainType*/ terrain, int position) const
  2545. {
  2546. CStack * ret = new CStack(&base, attackerOwned ? side1 : side2, stackID, attackerOwned, slot);
  2547. //native terrain bonuses
  2548. int faction = ret->type->faction;
  2549. if(faction >= 0 && VLC->heroh->nativeTerrains[faction] == terrain)
  2550. {
  2551. ret->bonuses.push_back(makeFeature(Bonus::STACKS_SPEED, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_NATIVE));
  2552. ret->bonuses.push_back(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::ATTACK, 1, Bonus::TERRAIN_NATIVE));
  2553. ret->bonuses.push_back(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::DEFENSE, 1, Bonus::TERRAIN_NATIVE));
  2554. }
  2555. ret->position = position;
  2556. return ret;
  2557. }
  2558. ui32 BattleInfo::getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  2559. {
  2560. ui32 ret = caster->getSpellCost(sp);
  2561. //checking for friendly stacks reducing cost of the spell and
  2562. //enemy stacks increasing it
  2563. si32 manaReduction = 0;
  2564. si32 manaIncrease = 0;
  2565. for(int g=0; g<stacks.size(); ++g)
  2566. {
  2567. if( stacks[g]->owner == caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY) )
  2568. {
  2569. amin(manaReduction, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  2570. }
  2571. if( stacks[g]->owner != caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY) )
  2572. {
  2573. amax(manaIncrease, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  2574. }
  2575. }
  2576. return ret + manaReduction + manaIncrease;
  2577. }
  2578. int BattleInfo::hexToWallPart(int hex) const
  2579. {
  2580. if(siege == 0) //there is no battle!
  2581. return -1;
  2582. static const std::pair<int, int> attackable[] = //potentially attackable parts of wall
  2583. {std::make_pair(50, 0), std::make_pair(183, 1), std::make_pair(182, 2), std::make_pair(130, 3),
  2584. 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)};
  2585. for(int g = 0; g < ARRAY_COUNT(attackable); ++g)
  2586. {
  2587. if(attackable[g].first == hex)
  2588. return attackable[g].second;
  2589. }
  2590. return -1; //not found!
  2591. }
  2592. int BattleInfo::lineToWallHex( int line ) const
  2593. {
  2594. static const int lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
  2595. return lineToHex[line];
  2596. }
  2597. std::pair<const CStack *, int> BattleInfo::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  2598. {
  2599. bool ac[BFIELD_SIZE];
  2600. std::set<int> occupyable;
  2601. getAccessibilityMap(ac, closest->doubleWide(), closest->attackerOwned, false, occupyable, closest->hasBonusOfType(Bonus::FLYING), closest->ID);
  2602. int predecessor[BFIELD_SIZE], dist[BFIELD_SIZE];
  2603. makeBFS(closest->position, ac, predecessor, dist, closest->doubleWide(), closest->attackerOwned, closest->hasBonusOfType(Bonus::FLYING), true);
  2604. std::vector< std::pair< std::pair<int, int>, const CStack *> > stackPairs; //pairs <<distance, hex>, stack>
  2605. for(int g=0; g<BFIELD_SIZE; ++g)
  2606. {
  2607. const CStack * atG = getStackT(g);
  2608. if(!atG || atG->ID == closest->ID) //if there is not stack or we are the closest one
  2609. continue;
  2610. if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  2611. {
  2612. if(predecessor[g] == -1) //TODO: is it really the best solution?
  2613. continue;
  2614. stackPairs.push_back( std::make_pair( std::make_pair(dist[predecessor[g]], g), atG) );
  2615. }
  2616. }
  2617. if(stackPairs.size() > 0)
  2618. {
  2619. std::vector< std::pair< std::pair<int, int>, const CStack *> > minimalPairs;
  2620. minimalPairs.push_back(stackPairs[0]);
  2621. for(int b=1; b<stackPairs.size(); ++b)
  2622. {
  2623. if(stackPairs[b].first.first < minimalPairs[0].first.first)
  2624. {
  2625. minimalPairs.clear();
  2626. minimalPairs.push_back(stackPairs[b]);
  2627. }
  2628. else if(stackPairs[b].first.first == minimalPairs[0].first.first)
  2629. {
  2630. minimalPairs.push_back(stackPairs[b]);
  2631. }
  2632. }
  2633. std::pair< std::pair<int, int>, const CStack *> minPair = minimalPairs[minimalPairs.size()/2];
  2634. return std::make_pair(minPair.second, predecessor[minPair.first.second]);
  2635. }
  2636. return std::make_pair<const CStack * , int>(NULL, -1);
  2637. }
  2638. ui32 BattleInfo::calculateSpellDmg( const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower ) const
  2639. {
  2640. ui32 ret = 0; //value to return
  2641. //15 - magic arrows, 16 - ice bolt, 17 - lightning bolt, 18 - implosion, 20 - frost ring, 21 - fireball, 22 - inferno, 23 - meteor shower,
  2642. //24 - death ripple, 25 - destroy undead, 26 - armageddon, 77 - thunderbolt
  2643. 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);
  2644. //check if spell really does damage - if not, return 0
  2645. if(dmgMultipliers.find(sp->id) == dmgMultipliers.end())
  2646. return 0;
  2647. ret = usedSpellPower * dmgMultipliers[sp->id];
  2648. ret += sp->powers[spellSchoolLevel];
  2649. //applying sorcerery secondary skill
  2650. if(caster)
  2651. {
  2652. switch(caster->getSecSkillLevel(25))
  2653. {
  2654. case 1: //basic
  2655. ret *= 1.05f;
  2656. break;
  2657. case 2: //advanced
  2658. ret *= 1.1f;
  2659. break;
  2660. case 3: //expert
  2661. ret *= 1.15f;
  2662. break;
  2663. }
  2664. }
  2665. //applying hero bonuses
  2666. if(sp->air && caster && caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY) != 0)
  2667. {
  2668. ret *= (100.0f + caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY)) / 100.0f;
  2669. }
  2670. else if(sp->fire && caster && caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY) != 0)
  2671. {
  2672. ret *= (100.0f + caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY)) / 100.0f;
  2673. }
  2674. else if(sp->water && caster && caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY) != 0)
  2675. {
  2676. ret *= (100.0f + caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY)) / 100.0f;
  2677. }
  2678. else if(sp->earth && caster && caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY) != 0)
  2679. {
  2680. ret *= (100.0f + caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY)) / 100.0f;
  2681. }
  2682. //affected creature-specific part
  2683. if(affectedCreature)
  2684. {
  2685. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  2686. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
  2687. {
  2688. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 0);
  2689. ret /= 100;
  2690. }
  2691. else if(sp->fire && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
  2692. {
  2693. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 1);
  2694. ret /= 100;
  2695. }
  2696. else if(sp->water && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
  2697. {
  2698. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 2);
  2699. ret /= 100;
  2700. }
  2701. else if (sp->earth && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
  2702. {
  2703. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 3);
  2704. ret /= 100;
  2705. }
  2706. //general spell dmg reduction
  2707. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1)) //air spell & protection from air
  2708. {
  2709. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  2710. ret /= 100;
  2711. }
  2712. //dmg increasing
  2713. if( affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id) )
  2714. {
  2715. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id);
  2716. ret /= 100;
  2717. }
  2718. }
  2719. return ret;
  2720. }
  2721. bool CGameState::battleCanShoot(int ID, int dest)
  2722. {
  2723. if(!curB)
  2724. return false;
  2725. const CStack *our = curB->getStack(ID),
  2726. *dst = curB->getStackT(dest);
  2727. if(!our || !dst) return false;
  2728. const CGHeroInstance * ourHero = battleGetOwner(our->ID);
  2729. if(our->hasBonusOfType(Bonus::FORGETFULL)) //forgetfulness
  2730. return false;
  2731. if(our->type->idNumber == 145 && dst) //catapult cannot attack creatures
  2732. return false;
  2733. if(our->hasBonusOfType(Bonus::SHOOTER)//it's shooter
  2734. && our->owner != dst->owner
  2735. && dst->alive()
  2736. && (!curB->isStackBlocked(ID) || NBonus::hasOfType(ourHero, Bonus::FREE_SHOOTING))
  2737. && our->shots
  2738. )
  2739. return true;
  2740. return false;
  2741. }
  2742. int CGameState::victoryCheck( ui8 player ) const
  2743. {
  2744. const PlayerState *p = getPlayer(player);
  2745. if(map->victoryCondition.condition == winStandard || map->victoryCondition.allowNormalVictory)
  2746. if(player == checkForStandardWin())
  2747. return -1;
  2748. if(p->human || map->victoryCondition.appliesToAI)
  2749. {
  2750. switch(map->victoryCondition.condition)
  2751. {
  2752. case artifact:
  2753. //check if any hero has winning artifact
  2754. for(size_t i = 0; i < p->heroes.size(); i++)
  2755. if(p->heroes[i]->hasArt(map->victoryCondition.ID))
  2756. return 1;
  2757. break;
  2758. case gatherTroop:
  2759. {
  2760. //check if in players armies there is enough creatures
  2761. int total = 0; //creature counter
  2762. for(size_t i = 0; i < map->objects.size(); i++)
  2763. {
  2764. const CArmedInstance *ai = NULL;
  2765. if(map->objects[i]
  2766. && map->objects[i]->tempOwner == player //object controlled by player
  2767. && (ai = dynamic_cast<const CArmedInstance*>(map->objects[i]))) //contains army
  2768. {
  2769. for(TSlots::const_iterator i=ai->Slots().begin(); i!=ai->Slots().end(); ++i) //iterate through army
  2770. if(i->second.type->idNumber == map->victoryCondition.ID) //it's searched creature
  2771. total += i->second.count;
  2772. }
  2773. }
  2774. if(total >= map->victoryCondition.count)
  2775. return 1;
  2776. }
  2777. break;
  2778. case gatherResource:
  2779. if(p->resources[map->victoryCondition.ID] >= map->victoryCondition.count)
  2780. return 1;
  2781. break;
  2782. case buildCity:
  2783. {
  2784. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  2785. if(t->tempOwner == player && t->fortLevel()-1 >= map->victoryCondition.ID && t->hallLevel()-1 >= map->victoryCondition.count)
  2786. return 1;
  2787. }
  2788. break;
  2789. case buildGrail:
  2790. BOOST_FOREACH(const CGTownInstance *t, map->towns)
  2791. if((t == map->victoryCondition.obj || !map->victoryCondition.obj)
  2792. && t->tempOwner == player
  2793. && vstd::contains(t->builtBuildings, 26))
  2794. return 1;
  2795. break;
  2796. case beatHero:
  2797. if(map->victoryCondition.obj->tempOwner >= PLAYER_LIMIT) //target hero not present on map
  2798. return 1;
  2799. break;
  2800. case captureCity:
  2801. {
  2802. if(map->victoryCondition.obj->tempOwner == player)
  2803. return 1;
  2804. }
  2805. break;
  2806. case beatMonster:
  2807. if(!map->objects[map->victoryCondition.obj->id]) //target monster not present on map
  2808. return 1;
  2809. break;
  2810. case takeDwellings:
  2811. for(size_t i = 0; i < map->objects.size(); i++)
  2812. {
  2813. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  2814. {
  2815. switch(map->objects[i]->ID)
  2816. {
  2817. case 17: case 18: case 19: case 20: //dwellings
  2818. case 216: case 217: case 218:
  2819. return 0; //found not flagged dwelling - player not won
  2820. }
  2821. }
  2822. }
  2823. return 1;
  2824. break;
  2825. case takeMines:
  2826. for(size_t i = 0; i < map->objects.size(); i++)
  2827. {
  2828. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  2829. {
  2830. switch(map->objects[i]->ID)
  2831. {
  2832. case 53: case 220:
  2833. return 0; //found not flagged mine - player not won
  2834. }
  2835. }
  2836. }
  2837. return 1;
  2838. break;
  2839. case transportItem:
  2840. {
  2841. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  2842. if(t->visitingHero && t->visitingHero->hasArt(map->victoryCondition.ID)
  2843. || t->garrisonHero && t->garrisonHero->hasArt(map->victoryCondition.ID))
  2844. {
  2845. return 1;
  2846. }
  2847. }
  2848. break;
  2849. }
  2850. }
  2851. return 0;
  2852. }
  2853. ui8 CGameState::checkForStandardWin() const
  2854. {
  2855. //std victory condition is:
  2856. //all enemies lost
  2857. ui8 supposedWinner = 255, winnerTeam = 255;
  2858. for(std::map<ui8,PlayerState>::const_iterator i = players.begin(); i != players.end(); i++)
  2859. {
  2860. if(i->second.status == PlayerState::INGAME && i->first < PLAYER_LIMIT)
  2861. {
  2862. if(supposedWinner == 255)
  2863. {
  2864. //first player remaining ingame - candidate for victory
  2865. supposedWinner = i->second.color;
  2866. winnerTeam = map->players[supposedWinner].team;
  2867. }
  2868. else if(winnerTeam != map->players[i->second.color].team)
  2869. {
  2870. //current candidate has enemy remaining in game -> no vicotry
  2871. return 255;
  2872. }
  2873. }
  2874. }
  2875. return supposedWinner;
  2876. }
  2877. bool CGameState::checkForStandardLoss( ui8 player ) const
  2878. {
  2879. //std loss condition is: player lost all towns and heroes
  2880. const PlayerState &p = *getPlayer(player);
  2881. return !p.heroes.size() && !p.towns.size();
  2882. }
  2883. struct statsHLP
  2884. {
  2885. typedef std::pair< ui8, si64 > TStat;
  2886. //converts [<player's color, value>] to vec[place] -> platers
  2887. static std::vector< std::list< ui8 > > getRank( std::vector<TStat> stats )
  2888. {
  2889. std::sort(stats.begin(), stats.end(), statsHLP());
  2890. //put first element
  2891. std::vector< std::list<ui8> > ret;
  2892. std::list<ui8> tmp;
  2893. tmp.push_back( stats[0].first );
  2894. ret.push_back( tmp );
  2895. //the rest of elements
  2896. for(int g=1; g<stats.size(); ++g)
  2897. {
  2898. if(stats[g].second == stats[g-1].second)
  2899. {
  2900. (ret.end()-1)->push_back( stats[g].first );
  2901. }
  2902. else
  2903. {
  2904. //create next occupied rank
  2905. std::list<ui8> tmp;
  2906. tmp.push_back(stats[g].first);
  2907. ret.push_back(tmp);
  2908. }
  2909. }
  2910. return ret;
  2911. }
  2912. bool operator()(const TStat & a, const TStat & b) const
  2913. {
  2914. return a.second > b.second;
  2915. }
  2916. static const CGHeroInstance * findBestHero(CGameState * gs, int color)
  2917. {
  2918. std::vector<CGHeroInstance *> &h = gs->players[color].heroes;
  2919. if(!h.size())
  2920. return NULL;
  2921. //best hero will be that with highest exp
  2922. int best = 0;
  2923. for(int b=1; b<h.size(); ++b)
  2924. {
  2925. if(h[b]->exp > h[best]->exp)
  2926. {
  2927. best = b;
  2928. }
  2929. }
  2930. return h[best];
  2931. }
  2932. //calculates total number of artifacts that belong to given player
  2933. static int getNumberOfArts(const PlayerState * ps)
  2934. {
  2935. int ret = 0;
  2936. for(int g=0; g<ps->heroes.size(); ++g)
  2937. {
  2938. ret += ps->heroes[g]->artifacts.size() + ps->heroes[g]->artifWorn.size();
  2939. }
  2940. return ret;
  2941. }
  2942. };
  2943. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  2944. {
  2945. #define FILL_FIELD(FIELD, VAL_GETTER) \
  2946. { \
  2947. std::vector< std::pair< ui8, si64 > > stats; \
  2948. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g) \
  2949. { \
  2950. if(g->second.color == 255) \
  2951. continue; \
  2952. std::pair< ui8, si64 > stat; \
  2953. stat.first = g->second.color; \
  2954. stat.second = VAL_GETTER; \
  2955. stats.push_back(stat); \
  2956. } \
  2957. tgi.FIELD = statsHLP::getRank(stats); \
  2958. }
  2959. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2960. {
  2961. if(g->second.color != 255)
  2962. tgi.playerColors.push_back(g->second.color);
  2963. }
  2964. if(level >= 1) //num of towns & num of heroes
  2965. {
  2966. //num of towns
  2967. FILL_FIELD(numOfTowns, g->second.towns.size())
  2968. //num of heroes
  2969. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2970. //best hero's portrait
  2971. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2972. {
  2973. if(g->second.color == 255)
  2974. continue;
  2975. const CGHeroInstance * best = statsHLP::findBestHero(this, g->second.color);
  2976. InfoAboutHero iah;
  2977. iah.initFromHero(best, level >= 8);
  2978. iah.army.clear();
  2979. tgi.colorToBestHero[g->second.color] = iah;
  2980. }
  2981. }
  2982. if(level >= 2) //gold
  2983. {
  2984. FILL_FIELD(gold, g->second.resources[6])
  2985. }
  2986. if(level >= 2) //wood & ore
  2987. {
  2988. FILL_FIELD(woodOre, g->second.resources[0] + g->second.resources[1])
  2989. }
  2990. if(level >= 3) //mercury, sulfur, crystal, gems
  2991. {
  2992. FILL_FIELD(mercSulfCrystGems, g->second.resources[2] + g->second.resources[3] + g->second.resources[4] + g->second.resources[5])
  2993. }
  2994. if(level >= 4) //obelisks found
  2995. {
  2996. //TODO
  2997. }
  2998. if(level >= 5) //artifacts
  2999. {
  3000. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  3001. }
  3002. if(level >= 6) //army strength
  3003. {
  3004. //TODO
  3005. }
  3006. if(level >= 7) //income
  3007. {
  3008. //TODO
  3009. }
  3010. if(level >= 8) //best hero's stats
  3011. {
  3012. //already set in lvl 1 handling
  3013. }
  3014. if(level >= 9) //personality
  3015. {
  3016. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  3017. {
  3018. if(g->second.color == 255) //do nothing for neutral player
  3019. continue;
  3020. if(g->second.human)
  3021. {
  3022. tgi.personality[g->second.color] = -1;
  3023. }
  3024. else //AI
  3025. {
  3026. tgi.personality[g->second.color] = map->players[g->second.serial].AITactic;
  3027. }
  3028. }
  3029. }
  3030. if(level >= 10) //best creature
  3031. {
  3032. //best creatures belonging to player (highest AI value)
  3033. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  3034. {
  3035. if(g->second.color == 255) //do nothing for neutral player
  3036. continue;
  3037. int bestCre = -1; //best creature's ID
  3038. for(int b=0; b<g->second.heroes.size(); ++b)
  3039. {
  3040. for(TSlots::const_iterator it = g->second.heroes[b]->Slots().begin(); it != g->second.heroes[b]->Slots().end(); ++it)
  3041. {
  3042. int toCmp = it->second.type->idNumber; //ID of creature we should compare with the best one
  3043. if(bestCre == -1 || VLC->creh->creatures[bestCre]->AIValue < VLC->creh->creatures[toCmp]->AIValue)
  3044. {
  3045. bestCre = toCmp;
  3046. }
  3047. }
  3048. }
  3049. tgi.bestCreature[g->second.color] = bestCre;
  3050. }
  3051. }
  3052. #undef FILL_FIELD
  3053. }
  3054. int CGameState::lossCheck( ui8 player ) const
  3055. {
  3056. const PlayerState *p = getPlayer(player);
  3057. //if(map->lossCondition.typeOfLossCon == lossStandard)
  3058. if(checkForStandardLoss(player))
  3059. return -1;
  3060. if(p->human) //special loss condition applies only to human player
  3061. {
  3062. switch(map->lossCondition.typeOfLossCon)
  3063. {
  3064. case lossCastle:
  3065. {
  3066. const CGTownInstance *t = dynamic_cast<const CGTownInstance *>(map->lossCondition.obj);
  3067. assert(t);
  3068. if(t->tempOwner != player)
  3069. return 1;
  3070. }
  3071. break;
  3072. case lossHero:
  3073. {
  3074. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(map->lossCondition.obj);
  3075. assert(h);
  3076. if(h->tempOwner != player)
  3077. return 1;
  3078. }
  3079. break;
  3080. case timeExpires:
  3081. if(map->lossCondition.timeLimit < day)
  3082. return 1;
  3083. break;
  3084. }
  3085. }
  3086. if(!p->towns.size() && p->daysWithoutCastle >= 7)
  3087. return 2;
  3088. return false;
  3089. }
  3090. std::map<ui32,CGHeroInstance *> CGameState::unusedHeroesFromPool()
  3091. {
  3092. std::map<ui32,CGHeroInstance *> pool = hpool.heroesPool;
  3093. for ( std::map<ui8, PlayerState>::iterator i = players.begin() ; i != players.end();i++)
  3094. for(std::vector<CGHeroInstance *>::iterator j = i->second.availableHeroes.begin(); j != i->second.availableHeroes.end(); j++)
  3095. if(*j)
  3096. pool.erase((**j).subID);
  3097. return pool;
  3098. }
  3099. const CStack * BattleInfo::getNextStack() const
  3100. {
  3101. std::vector<const CStack *> hlp;
  3102. getStackQueue(hlp, 1, -1);
  3103. if(hlp.size())
  3104. return hlp[0];
  3105. else
  3106. return NULL;
  3107. }
  3108. static const CStack *takeStack(std::vector<const CStack *> &st, int &curside, int turn)
  3109. {
  3110. const CStack *ret = NULL;
  3111. unsigned i, //fastest stack
  3112. j; //fastest stack of the other side
  3113. for(i = 0; i < st.size(); i++)
  3114. if(st[i])
  3115. break;
  3116. //no stacks left
  3117. if(i == st.size())
  3118. return NULL;
  3119. const CStack *fastest = st[i], *other = NULL;
  3120. int bestSpeed = fastest->Speed(turn);
  3121. if(fastest->attackerOwned != curside)
  3122. {
  3123. ret = fastest;
  3124. }
  3125. else
  3126. {
  3127. for(j = i + 1; j < st.size(); j++)
  3128. {
  3129. if(!st[j]) continue;
  3130. if(st[j]->attackerOwned != curside || st[j]->Speed(turn) != bestSpeed)
  3131. break;
  3132. }
  3133. if(j >= st.size())
  3134. {
  3135. ret = fastest;
  3136. }
  3137. else
  3138. {
  3139. other = st[j];
  3140. if(other->Speed(turn) != bestSpeed)
  3141. ret = fastest;
  3142. else
  3143. ret = other;
  3144. }
  3145. }
  3146. assert(ret);
  3147. if(ret == fastest)
  3148. st[i] = NULL;
  3149. else
  3150. st[j] = NULL;
  3151. curside = ret->attackerOwned;
  3152. return ret;
  3153. }
  3154. void BattleInfo::getStackQueue( std::vector<const CStack *> &out, int howMany, int turn /*= 0*/, int lastMoved /*= -1*/ ) const
  3155. {
  3156. //we'll split creatures with remaining movement to 4 parts
  3157. 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
  3158. int toMove = 0; //how many stacks still has move
  3159. const CStack *active = getStack(activeStack);
  3160. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  3161. if(!turn && active && active->willMove() && !vstd::contains(active->state, WAITING))
  3162. {
  3163. out.push_back(active);
  3164. if(out.size() == howMany)
  3165. return;
  3166. }
  3167. for(unsigned int i=0; i<stacks.size(); ++i)
  3168. {
  3169. const CStack * const s = stacks[i];
  3170. if(turn <= 0 && !s->willMove() //we are considering current round and stack won't move
  3171. || turn > 0 && !s->canMove(turn) //stack won't be able to move in later rounds
  3172. || turn <= 0 && s == active && out.size() && s == out.front()) //it's active stack already added at the beginning of queue
  3173. {
  3174. continue;
  3175. }
  3176. int p = -1; //in which phase this tack will move?
  3177. if(turn <= 0 && vstd::contains(s->state, WAITING)) //consider waiting state only for ongoing round
  3178. {
  3179. if(vstd::contains(s->state, HAD_MORALE))
  3180. p = 2;
  3181. else
  3182. p = 3;
  3183. }
  3184. else if(s->type->idNumber == 145 || s->type->idNumber == 149) //catapult and turrets are first
  3185. {
  3186. p = 0;
  3187. }
  3188. else
  3189. {
  3190. p = 1;
  3191. }
  3192. phase[p].push_back(s);
  3193. toMove++;
  3194. }
  3195. for(int i = 0; i < 4; i++)
  3196. std::sort(phase[i].begin(), phase[i].end(), CMP_stack(i, turn > 0 ? turn : 0));
  3197. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  3198. out.push_back(phase[0][i]);
  3199. if(out.size() == howMany)
  3200. return;
  3201. if(lastMoved == -1)
  3202. {
  3203. if(active)
  3204. {
  3205. if(out.size() && out.front() == active)
  3206. lastMoved = active->attackerOwned;
  3207. else
  3208. lastMoved = active->attackerOwned;
  3209. }
  3210. else
  3211. {
  3212. lastMoved = 0;
  3213. }
  3214. }
  3215. int pi = 1;
  3216. while(out.size() < howMany)
  3217. {
  3218. const CStack *hlp = takeStack(phase[pi], lastMoved, turn);
  3219. if(!hlp)
  3220. {
  3221. pi++;
  3222. if(pi > 3)
  3223. {
  3224. //if(turn != 2)
  3225. getStackQueue(out, howMany, turn + 1, lastMoved);
  3226. return;
  3227. }
  3228. }
  3229. else
  3230. {
  3231. out.push_back(hlp);
  3232. }
  3233. }
  3234. }
  3235. si8 BattleInfo::hasDistancePenalty( int stackID, int destHex )
  3236. {
  3237. const CStack * stack = getStack(stackID);
  3238. int distance = std::abs(destHex % BFIELD_WIDTH - stack->position % BFIELD_WIDTH);
  3239. //I hope it's approximately correct
  3240. return distance > 8 && !stack->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY);
  3241. }
  3242. si8 BattleInfo::sameSideOfWall(int pos1, int pos2)
  3243. {
  3244. int wallInStackLine = lineToWallHex(pos1/BFIELD_WIDTH);
  3245. int wallInDestLine = lineToWallHex(pos2/BFIELD_WIDTH);
  3246. bool stackLeft = pos1 < wallInStackLine;
  3247. bool destLeft = pos2 < wallInDestLine;
  3248. return stackLeft != destLeft;
  3249. }
  3250. si8 BattleInfo::hasWallPenalty( int stackID, int destHex )
  3251. {
  3252. if (siege == 0)
  3253. {
  3254. return false;
  3255. }
  3256. const CStack * stack = getStack(stackID);
  3257. if (stack->hasBonusOfType(Bonus::NO_WALL_PENALTY));
  3258. {
  3259. return false;
  3260. }
  3261. return !sameSideOfWall(stack->position, destHex);
  3262. }
  3263. si8 BattleInfo::canTeleportTo(int stackID, int destHex, int telportLevel)
  3264. {
  3265. bool ac[BFIELD_SIZE];
  3266. const CStack *s = getStack(stackID, false); //this function is called from healedOrResurrected, so our stack can be dead
  3267. std::set<int> occupyable;
  3268. getAccessibilityMap(ac, s->doubleWide(), s->attackerOwned, false, occupyable, s->hasBonusOfType(Bonus::FLYING), stackID);
  3269. if (siege && telportLevel < 2) //check for wall
  3270. {
  3271. return ac[destHex] && sameSideOfWall(s->position, destHex);
  3272. }
  3273. else
  3274. {
  3275. return ac[destHex];
  3276. }
  3277. }
  3278. void BattleInfo::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  3279. {
  3280. CBonusSystemNode::getBonuses(out, selector, root);
  3281. const CStack *dest = dynamic_cast<const CStack*>(root);
  3282. if (!dest)
  3283. return;
  3284. //TODO: make it in clean way
  3285. if(Selector::matchesType(selector, Bonus::MORALE) || Selector::matchesType(selector, Bonus::LUCK))
  3286. {
  3287. BOOST_FOREACH(const CStack *s, stacks)
  3288. {
  3289. if(s->owner == dest->owner)
  3290. s->getBonuses(out, selector, Selector::effectRange(Bonus::ONLY_ALLIED_ARMY), this);
  3291. else
  3292. s->getBonuses(out, selector, Selector::effectRange(Bonus::ONLY_ENEMY_ARMY), this);
  3293. }
  3294. }
  3295. }
  3296. int3 CPath::startPos() const
  3297. {
  3298. return nodes[nodes.size()-1].coord;
  3299. }
  3300. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  3301. {
  3302. if (mode==0)
  3303. {
  3304. for (unsigned int i=0;i<nodes.size();i++)
  3305. {
  3306. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  3307. }
  3308. }
  3309. }
  3310. int3 CPath::endPos() const
  3311. {
  3312. return nodes[0].coord;
  3313. }
  3314. CGPathNode::CGPathNode()
  3315. :coord(-1,-1,-1)
  3316. {
  3317. accessible = 0;
  3318. land = 0;
  3319. moveRemains = 0;
  3320. turns = 255;
  3321. theNodeBefore = NULL;
  3322. }
  3323. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  3324. {
  3325. out.nodes.clear();
  3326. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  3327. if(!curnode->theNodeBefore || curnode->accessible == CGPathNode::FLYABLE)
  3328. return false;
  3329. //we'll transform number of turns to conform the rule that hero cannot stop on blocked tile
  3330. bool transition01 = false;
  3331. while(curnode)
  3332. {
  3333. CGPathNode cpn = *curnode;
  3334. if(transition01)
  3335. {
  3336. if (curnode->accessible == CGPathNode::ACCESSIBLE)
  3337. {
  3338. transition01 = false;
  3339. }
  3340. else if (curnode->accessible == CGPathNode::FLYABLE)
  3341. {
  3342. cpn.turns = 1;
  3343. }
  3344. }
  3345. if(curnode->turns == 1 && curnode->theNodeBefore->turns == 0)
  3346. {
  3347. transition01 = true;
  3348. }
  3349. curnode = curnode->theNodeBefore;
  3350. out.nodes.push_back(cpn);
  3351. }
  3352. return true;
  3353. }
  3354. CPathsInfo::CPathsInfo( const int3 &Sizes )
  3355. :sizes(Sizes)
  3356. {
  3357. hero = NULL;
  3358. nodes = new CGPathNode**[sizes.x];
  3359. for(int i = 0; i < sizes.x; i++)
  3360. {
  3361. nodes[i] = new CGPathNode*[sizes.y];
  3362. for (int j = 0; j < sizes.y; j++)
  3363. {
  3364. nodes[i][j] = new CGPathNode[sizes.z];
  3365. }
  3366. }
  3367. }
  3368. CPathsInfo::~CPathsInfo()
  3369. {
  3370. for(int i = 0; i < sizes.x; i++)
  3371. {
  3372. for (int j = 0; j < sizes.y; j++)
  3373. {
  3374. delete [] nodes[i][j];
  3375. }
  3376. delete [] nodes[i];
  3377. }
  3378. delete [] nodes;
  3379. }
  3380. int3 CGPath::startPos() const
  3381. {
  3382. return nodes[nodes.size()-1].coord;
  3383. }
  3384. int3 CGPath::endPos() const
  3385. {
  3386. return nodes[0].coord;
  3387. }
  3388. void CGPath::convert( ui8 mode )
  3389. {
  3390. if(mode==0)
  3391. {
  3392. for(unsigned int i=0;i<nodes.size();i++)
  3393. {
  3394. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  3395. }
  3396. }
  3397. }
  3398. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  3399. {
  3400. switch(phase)
  3401. {
  3402. case 0: //catapult moves after turrets
  3403. return a->type->idNumber < b->type->idNumber; //catapult is 145 and turrets are 149
  3404. //TODO? turrets order
  3405. case 1: //fastest first, upper slot first
  3406. {
  3407. int as = a->Speed(turn), bs = b->Speed(turn);
  3408. if(as != bs)
  3409. return as > bs;
  3410. else
  3411. return a->slot < b->slot;
  3412. }
  3413. case 2: //fastest last, upper slot first
  3414. //TODO: should be replaced with order of receiving morale!
  3415. case 3: //fastest last, upper slot first
  3416. {
  3417. int as = a->Speed(turn), bs = b->Speed(turn);
  3418. if(as != bs)
  3419. return as < bs;
  3420. else
  3421. return a->slot < b->slot;
  3422. }
  3423. default:
  3424. assert(0);
  3425. return false;
  3426. }
  3427. }
  3428. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  3429. {
  3430. phase = Phase;
  3431. turn = Turn;
  3432. }
  3433. PlayerState::PlayerState()
  3434. : color(-1), currentSelection(0xffffffff), status(INGAME), daysWithoutCastle(0)
  3435. {
  3436. }
  3437. void PlayerState::getParents(TCNodes &out, const CBonusSystemNode *root /*= NULL*/) const
  3438. {
  3439. /*
  3440. for (std::vector<CGHeroInstance *>::const_iterator it = heroes.begin(); it != heroes.end(); ++it)
  3441. {
  3442. if (*it != root)
  3443. (*it)->getParents(out, root);
  3444. }
  3445. for (std::vector<CGTownInstance *>::const_iterator it = towns.begin(); it != towns.end(); ++it)
  3446. {
  3447. if (*it != root)
  3448. (*it)->getParents(out, root);
  3449. }
  3450. */
  3451. //TODO - dwellings
  3452. }
  3453. void PlayerState::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  3454. {//temporary
  3455. //CBonusSystemNode::getBonuses(out, selector, root);
  3456. }
  3457. InfoAboutHero::InfoAboutHero()
  3458. {
  3459. details = NULL;
  3460. hclass = NULL;
  3461. portrait = -1;
  3462. }
  3463. InfoAboutHero::InfoAboutHero( const InfoAboutHero & iah )
  3464. {
  3465. assign(iah);
  3466. }
  3467. InfoAboutHero::~InfoAboutHero()
  3468. {
  3469. delete details;
  3470. }
  3471. void InfoAboutHero::initFromHero( const CGHeroInstance *h, bool detailed )
  3472. {
  3473. if(!h) return;
  3474. owner = h->tempOwner;
  3475. hclass = h->type->heroClass;
  3476. name = h->name;
  3477. portrait = h->portrait;
  3478. army = h->getArmy();
  3479. if(detailed)
  3480. {
  3481. //include details about hero
  3482. details = new Details;
  3483. details->luck = h->LuckVal();
  3484. details->morale = h->MoraleVal();
  3485. details->mana = h->mana;
  3486. details->primskills.resize(PRIMARY_SKILLS);
  3487. for (int i = 0; i < PRIMARY_SKILLS ; i++)
  3488. {
  3489. details->primskills[i] = h->getPrimSkillLevel(i);
  3490. }
  3491. }
  3492. else
  3493. {
  3494. //hide info about hero stacks counts using descriptives names ids
  3495. for(TSlots::const_iterator i = army.Slots().begin(); i != army.Slots().end(); ++i)
  3496. {
  3497. army.setStackCount(i->first, i->second.getQuantityID()+1);
  3498. }
  3499. }
  3500. }
  3501. void InfoAboutHero::assign( const InfoAboutHero & iah )
  3502. {
  3503. army = iah.army;
  3504. details = (iah.details ? new Details(*iah.details) : NULL);
  3505. hclass = iah.hclass;
  3506. name = iah.name;
  3507. owner = iah.owner;
  3508. portrait = iah.portrait;
  3509. }
  3510. InfoAboutHero & InfoAboutHero::operator=( const InfoAboutHero & iah )
  3511. {
  3512. assign(iah);
  3513. return *this;
  3514. }
  3515. void CCampaignState::initNewCampaign( const StartInfo &si )
  3516. {
  3517. assert(si.mode == 2);
  3518. campaignName = si.mapname;
  3519. currentMap = si.whichMapInCampaign;
  3520. camp = CCampaignHandler::getCampaign(campaignName, true); //TODO lod???
  3521. for (ui8 i = 0; i < camp->mapPieces.size(); i++)
  3522. mapsRemaining.push_back(i);
  3523. }