CGameState.cpp 108 KB

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