CGameState.cpp 105 KB

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