CGameState.cpp 105 KB

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