CGameState.cpp 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226
  1. #include "StdInc.h"
  2. #include "CGameState.h"
  3. #include <boost/random/linear_congruential.hpp>
  4. #include "Mapping/CCampaignHandler.h"
  5. #include "CDefObjInfoHandler.h"
  6. #include "CArtHandler.h"
  7. #include "CBuildingHandler.h"
  8. #include "CGeneralTextHandler.h"
  9. #include "CTownHandler.h"
  10. #include "CSpellHandler.h"
  11. #include "CHeroHandler.h"
  12. #include "CObjectHandler.h"
  13. #include "CCreatureHandler.h"
  14. #include "CModHandler.h"
  15. #include "VCMI_Lib.h"
  16. #include "Connection.h"
  17. #include "Mapping/CMap.h"
  18. #include "Mapping/CMapService.h"
  19. #include "StartInfo.h"
  20. #include "NetPacks.h"
  21. #include "RegisterTypes.h"
  22. #include "Mapping/CMapInfo.h"
  23. #include "BattleState.h"
  24. #include "JsonNode.h"
  25. #include "Filesystem/CResourceLoader.h"
  26. #include "GameConstants.h"
  27. #include "RMG/CMapGenOptions.h"
  28. DLL_LINKAGE boost::rand48 ran;
  29. class CGObjectInstance;
  30. #ifdef min
  31. #undef min
  32. #endif
  33. #ifdef max
  34. #undef max
  35. #endif
  36. /*
  37. * CGameState.cpp, part of VCMI engine
  38. *
  39. * Authors: listed in file AUTHORS in main folder
  40. *
  41. * License: GNU General Public License v2.0 or later
  42. * Full text of license available in license.txt file, in main folder
  43. *
  44. */
  45. void foofoofoo()
  46. {
  47. //never called function to force instantation of templates
  48. int *ccc = NULL;
  49. registerTypes((CISer<CConnection>&)*ccc);
  50. registerTypes((COSer<CConnection>&)*ccc);
  51. registerTypes((CSaveFile&)*ccc);
  52. registerTypes((CLoadFile&)*ccc);
  53. registerTypes((CTypeList&)*ccc);
  54. }
  55. template <typename T> class CApplyOnGS;
  56. class CBaseForGSApply
  57. {
  58. public:
  59. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  60. virtual ~CBaseForGSApply(){};
  61. template<typename U> static CBaseForGSApply *getApplier(const U * t=NULL)
  62. {
  63. return new CApplyOnGS<U>;
  64. }
  65. };
  66. template <typename T> class CApplyOnGS : public CBaseForGSApply
  67. {
  68. public:
  69. void applyOnGS(CGameState *gs, void *pack) const
  70. {
  71. T *ptr = static_cast<T*>(pack);
  72. boost::unique_lock<boost::shared_mutex> lock(*gs->mx);
  73. ptr->applyGs(gs);
  74. }
  75. };
  76. static CApplier<CBaseForGSApply> *applierGs = NULL;
  77. class IObjectCaller
  78. {
  79. public:
  80. virtual ~IObjectCaller(){};
  81. virtual void preInit()=0;
  82. virtual void postInit()=0;
  83. };
  84. template <typename T>
  85. class CObjectCaller : public IObjectCaller
  86. {
  87. public:
  88. void preInit()
  89. {
  90. //T::preInit();
  91. }
  92. void postInit()
  93. {
  94. //T::postInit();
  95. }
  96. };
  97. class CObjectCallersHandler
  98. {
  99. public:
  100. std::vector<IObjectCaller*> apps;
  101. template<typename T> void registerType(const T * t=NULL)
  102. {
  103. apps.push_back(new CObjectCaller<T>);
  104. }
  105. CObjectCallersHandler()
  106. {
  107. registerTypes1(*this);
  108. }
  109. ~CObjectCallersHandler()
  110. {
  111. for (size_t i = 0; i < apps.size(); i++)
  112. delete apps[i];
  113. }
  114. void preInit()
  115. {
  116. // for (size_t i = 0; i < apps.size(); i++)
  117. // apps[i]->preInit();
  118. }
  119. void postInit()
  120. {
  121. //for (size_t i = 0; i < apps.size(); i++)
  122. //apps[i]->postInit();
  123. }
  124. } *objCaller = NULL;
  125. void MetaString::getLocalString(const std::pair<ui8,ui32> &txt, std::string &dst) const
  126. {
  127. int type = txt.first, ser = txt.second;
  128. if(type == ART_NAMES)
  129. {
  130. dst = VLC->arth->artifacts[ser]->Name();
  131. }
  132. else if(type == CRE_PL_NAMES)
  133. {
  134. dst = VLC->creh->creatures[ser]->namePl;
  135. }
  136. else if(type == MINE_NAMES)
  137. {
  138. dst = VLC->generaltexth->mines[ser].first;
  139. }
  140. else if(type == MINE_EVNTS)
  141. {
  142. dst = VLC->generaltexth->mines[ser].second;
  143. }
  144. else if(type == SPELL_NAME)
  145. {
  146. dst = VLC->spellh->spells[ser]->name;
  147. }
  148. else if(type == CRE_SING_NAMES)
  149. {
  150. dst = VLC->creh->creatures[ser]->nameSing;
  151. }
  152. else if(type == ART_DESCR)
  153. {
  154. dst = VLC->arth->artifacts[ser]->Description();
  155. }
  156. else if (type == ART_EVNTS)
  157. {
  158. dst = VLC->arth->artifacts[ser]->EventText();
  159. }
  160. else
  161. {
  162. std::vector<std::string> *vec;
  163. switch(type)
  164. {
  165. case GENERAL_TXT:
  166. vec = &VLC->generaltexth->allTexts;
  167. break;
  168. case XTRAINFO_TXT:
  169. vec = &VLC->generaltexth->xtrainfo;
  170. break;
  171. case OBJ_NAMES:
  172. vec = &VLC->generaltexth->names;
  173. break;
  174. case RES_NAMES:
  175. vec = &VLC->generaltexth->restypes;
  176. break;
  177. case ARRAY_TXT:
  178. vec = &VLC->generaltexth->arraytxt;
  179. break;
  180. case CREGENS:
  181. vec = &VLC->generaltexth->creGens;
  182. break;
  183. case CREGENS4:
  184. vec = &VLC->generaltexth->creGens4;
  185. break;
  186. case ADVOB_TXT:
  187. vec = &VLC->generaltexth->advobtxt;
  188. break;
  189. case SEC_SKILL_NAME:
  190. vec = &VLC->generaltexth->skillName;
  191. break;
  192. case COLOR:
  193. vec = &VLC->generaltexth->capColors;
  194. break;
  195. default:
  196. tlog1 << "Failed string substitution because type is " << type << std::endl;
  197. dst = "#@#";
  198. return;
  199. }
  200. if(vec->size() <= ser)
  201. {
  202. tlog1 << "Failed string substitution with type " << type << " because index " << ser << " is out of bounds!\n";
  203. dst = "#!#";
  204. }
  205. else
  206. dst = (*vec)[ser];
  207. }
  208. }
  209. DLL_LINKAGE void MetaString::toString(std::string &dst) const
  210. {
  211. size_t exSt = 0, loSt = 0, nums = 0;
  212. dst.clear();
  213. for(size_t i=0;i<message.size();++i)
  214. {//TEXACT_STRING, TLOCAL_STRING, TNUMBER, TREPLACE_ESTRING, TREPLACE_LSTRING, TREPLACE_NUMBER
  215. switch(message[i])
  216. {
  217. case TEXACT_STRING:
  218. dst += exactStrings[exSt++];
  219. break;
  220. case TLOCAL_STRING:
  221. {
  222. std::string hlp;
  223. getLocalString(localStrings[loSt++], hlp);
  224. dst += hlp;
  225. }
  226. break;
  227. case TNUMBER:
  228. dst += boost::lexical_cast<std::string>(numbers[nums++]);
  229. break;
  230. case TREPLACE_ESTRING:
  231. boost::replace_first(dst, "%s", exactStrings[exSt++]);
  232. break;
  233. case TREPLACE_LSTRING:
  234. {
  235. std::string hlp;
  236. getLocalString(localStrings[loSt++], hlp);
  237. boost::replace_first(dst, "%s", hlp);
  238. }
  239. break;
  240. case TREPLACE_NUMBER:
  241. boost::replace_first(dst, "%d", boost::lexical_cast<std::string>(numbers[nums++]));
  242. break;
  243. case TREPLACE_PLUSNUMBER:
  244. boost::replace_first(dst, "%+d", '+' + boost::lexical_cast<std::string>(numbers[nums++]));
  245. break;
  246. default:
  247. tlog1 << "MetaString processing error!\n";
  248. break;
  249. }
  250. }
  251. }
  252. DLL_LINKAGE std::string MetaString::toString() const
  253. {
  254. std::string ret;
  255. toString(ret);
  256. return ret;
  257. }
  258. DLL_LINKAGE std::string MetaString::buildList () const
  259. ///used to handle loot from creature bank
  260. {
  261. size_t exSt = 0, loSt = 0, nums = 0;
  262. std::string lista;
  263. for (int i = 0; i < message.size(); ++i)
  264. {
  265. if (i > 0 && (message[i] == TEXACT_STRING || message[i] == TLOCAL_STRING))
  266. {
  267. if (exSt == exactStrings.size() - 1)
  268. lista += VLC->generaltexth->allTexts[141]; //" and "
  269. else
  270. lista += ", ";
  271. }
  272. switch (message[i])
  273. {
  274. case TEXACT_STRING:
  275. lista += exactStrings[exSt++];
  276. break;
  277. case TLOCAL_STRING:
  278. {
  279. std::string hlp;
  280. getLocalString (localStrings[loSt++], hlp);
  281. lista += hlp;
  282. }
  283. break;
  284. case TNUMBER:
  285. lista += boost::lexical_cast<std::string>(numbers[nums++]);
  286. break;
  287. case TREPLACE_ESTRING:
  288. lista.replace (lista.find("%s"), 2, exactStrings[exSt++]);
  289. break;
  290. case TREPLACE_LSTRING:
  291. {
  292. std::string hlp;
  293. getLocalString (localStrings[loSt++], hlp);
  294. lista.replace (lista.find("%s"), 2, hlp);
  295. }
  296. break;
  297. case TREPLACE_NUMBER:
  298. lista.replace (lista.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  299. break;
  300. default:
  301. tlog1 << "MetaString processing error!\n";
  302. }
  303. }
  304. return lista;
  305. }
  306. void MetaString::addCreReplacement(TCreature id, TQuantity count) //adds sing or plural name;
  307. {
  308. if (!count)
  309. addReplacement (CRE_PL_NAMES, id); //no creatures - just empty name (eg. defeat Angels)
  310. else if (count == 1)
  311. addReplacement (CRE_SING_NAMES, id);
  312. else
  313. addReplacement (CRE_PL_NAMES, id);
  314. }
  315. void MetaString::addReplacement(const CStackBasicDescriptor &stack)
  316. {
  317. assert(stack.type); //valid type
  318. addCreReplacement(stack.type->idNumber, stack.count);
  319. }
  320. static CGObjectInstance * createObject(int id, int subid, int3 pos, int owner)
  321. {
  322. CGObjectInstance * nobj;
  323. switch(id)
  324. {
  325. case Obj::HERO:
  326. {
  327. CGHeroInstance * nobj = new CGHeroInstance();
  328. nobj->pos = pos;
  329. nobj->tempOwner = owner;
  330. nobj->subID = subid;
  331. //nobj->initHero(ran);
  332. return nobj;
  333. }
  334. case Obj::TOWN:
  335. nobj = new CGTownInstance;
  336. break;
  337. default: //rest of objects
  338. nobj = new CGObjectInstance;
  339. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  340. break;
  341. }
  342. nobj->ID = id;
  343. nobj->subID = subid;
  344. if(!nobj->defInfo)
  345. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  346. nobj->pos = pos;
  347. //nobj->state = NULL;//new CLuaObjectScript();
  348. nobj->tempOwner = owner;
  349. nobj->defInfo->id = id;
  350. nobj->defInfo->subid = subid;
  351. //assigning defhandler
  352. if(nobj->ID==Obj::HERO || nobj->ID==Obj::TOWN)
  353. return nobj;
  354. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  355. return nobj;
  356. }
  357. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native, TPlayerColor player, const CTown *town, bmap<ui32, ConstTransitivePtr<CGHeroInstance> > &available, const CHeroClass *bannedClass /*= NULL*/) const
  358. {
  359. CGHeroInstance *ret = NULL;
  360. if(player>=GameConstants::PLAYER_LIMIT)
  361. {
  362. tlog1 << "Cannot pick hero for " << town->typeID << ". Wrong owner!\n";
  363. return NULL;
  364. }
  365. std::vector<CGHeroInstance *> pool;
  366. if(native)
  367. {
  368. for(auto i=available.begin(); i!=available.end(); i++)
  369. {
  370. if(pavailable.find(i->first)->second & 1<<player
  371. && i->second->type->heroClass->faction == town->typeID)
  372. {
  373. pool.push_back(i->second); //get all available heroes
  374. }
  375. }
  376. if(!pool.size())
  377. {
  378. tlog1 << "Cannot pick native hero for " << int(player) << ". Picking any...\n";
  379. return pickHeroFor(false, player, town, available);
  380. }
  381. else
  382. {
  383. ret = pool[rand()%pool.size()];
  384. }
  385. }
  386. else
  387. {
  388. int sum=0, r;
  389. for(auto i=available.begin(); i!=available.end(); i++)
  390. {
  391. if ((!bannedClass && (pavailable.find(i->first)->second & (1<<player))) ||
  392. i->second->type->heroClass != bannedClass)
  393. {
  394. pool.push_back(i->second);
  395. sum += i->second->type->heroClass->selectionProbability[town->typeID]; //total weight
  396. }
  397. }
  398. if(!pool.size() || sum == 0)
  399. {
  400. tlog1 << "There are no heroes available for player " << player<<"!\n";
  401. return nullptr;
  402. }
  403. r = rand()%sum;
  404. for (ui32 i=0; i<pool.size(); i++)
  405. {
  406. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  407. if(r < 0)
  408. {
  409. ret = pool[i];
  410. break;
  411. }
  412. }
  413. if(!ret)
  414. ret = pool.back();
  415. }
  416. available.erase(ret->subID);
  417. return ret;
  418. }
  419. //void CGameState::apply(CPack * pack)
  420. //{
  421. // while(!mx->try_lock())
  422. // boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  423. // //applyNL(pack);
  424. // mx->unlock();
  425. //}
  426. int CGameState::pickHero(int owner)
  427. {
  428. int h=-1;
  429. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  430. if(!map->getHero(h = ps.hero) && h>=0) //we haven't used selected hero
  431. return h;
  432. if(scenarioOps->mode == StartInfo::CAMPAIGN)
  433. {
  434. auto bonus = scenarioOps->campState->getBonusForCurrentMap();
  435. if(bonus.is_initialized() && bonus->type == CScenarioTravel::STravelBonus::HERO && owner == bonus->info1)
  436. {
  437. if(bonus->info2 != 0xffff && !map->getHero(bonus->info2)) //not random and not taken
  438. {
  439. return bonus->info2;
  440. }
  441. }
  442. }
  443. //list of heroes for this faction
  444. std::vector<si32> factionHeroes;
  445. factionHeroes.reserve(GameConstants::HEROES_PER_TYPE*2);
  446. size_t firstHero = ps.castle*GameConstants::HEROES_PER_TYPE*2;
  447. size_t lastHero = std::min(firstHero + GameConstants::HEROES_PER_TYPE*2, VLC->heroh->heroes.size());
  448. //generate list of heroes
  449. for (si32 i=firstHero; i<lastHero; i++)
  450. factionHeroes.push_back(i);
  451. // we need random order to select hero
  452. std::random_shuffle(factionHeroes.begin(), factionHeroes.end(), [](size_t range)
  453. {
  454. return ran() % range;
  455. });
  456. for (size_t i=0; i<factionHeroes.size(); i++)
  457. {
  458. if (!map->getHero(factionHeroes[i]))
  459. return factionHeroes[i];
  460. }
  461. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  462. for(int j=0; j<VLC->heroh->heroes.size(); j++)
  463. if(!map->getHero(j))
  464. return j;
  465. assert(0); //currrent code can't handle this situation
  466. return -1; // no available heroes at all
  467. }
  468. std::pair<int,int> CGameState::pickObject (CGObjectInstance *obj)
  469. {
  470. switch(obj->ID)
  471. {
  472. case Obj::RANDOM_ART:
  473. return std::pair<int,int>(Obj::ARTIFACT, VLC->arth->getRandomArt (CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR | CArtifact::ART_RELIC));
  474. case Obj::RANDOM_TREASURE_ART:
  475. return std::pair<int,int>(Obj::ARTIFACT, VLC->arth->getRandomArt (CArtifact::ART_TREASURE));
  476. case Obj::RANDOM_MINOR_ART:
  477. return std::pair<int,int>(Obj::ARTIFACT, VLC->arth->getRandomArt (CArtifact::ART_MINOR));
  478. case Obj::RANDOM_MAJOR_ART:
  479. return std::pair<int,int>(Obj::ARTIFACT, VLC->arth->getRandomArt (CArtifact::ART_MAJOR));
  480. case Obj::RANDOM_RELIC_ART:
  481. return std::pair<int,int>(Obj::ARTIFACT, VLC->arth->getRandomArt (CArtifact::ART_RELIC));
  482. case Obj::RANDOM_HERO:
  483. return std::pair<int,int>(Obj::HERO, pickHero(obj->tempOwner));
  484. case Obj::RANDOM_MONSTER:
  485. return std::pair<int,int>(Obj::MONSTER, VLC->creh->pickRandomMonster(boost::ref(ran)));
  486. case Obj::RANDOM_MONSTER_L1:
  487. return std::pair<int,int>(Obj::MONSTER, VLC->creh->pickRandomMonster(boost::ref(ran), 1));
  488. case Obj::RANDOM_MONSTER_L2:
  489. return std::pair<int,int>(Obj::MONSTER, VLC->creh->pickRandomMonster(boost::ref(ran), 2));
  490. case Obj::RANDOM_MONSTER_L3:
  491. return std::pair<int,int>(Obj::MONSTER, VLC->creh->pickRandomMonster(boost::ref(ran), 3));
  492. case Obj::RANDOM_MONSTER_L4:
  493. return std::pair<int,int>(Obj::MONSTER, VLC->creh->pickRandomMonster(boost::ref(ran), 4));
  494. case Obj::RANDOM_RESOURCE:
  495. return std::pair<int,int>(Obj::RESOURCE,ran()%7); //now it's OH3 style, use %8 for mithril
  496. case Obj::RANDOM_TOWN:
  497. {
  498. int align = (static_cast<CGTownInstance*>(obj))->alignment,
  499. f;
  500. if(align>GameConstants::PLAYER_LIMIT-1)//same as owner / random
  501. {
  502. if(obj->tempOwner > GameConstants::PLAYER_LIMIT-1)
  503. f = -1; //random
  504. else
  505. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  506. }
  507. else
  508. {
  509. f = scenarioOps->getIthPlayersSettings(align).castle;
  510. }
  511. if(f<0)
  512. {
  513. auto iter = VLC->townh->towns.begin();
  514. std::advance(iter, ran()%VLC->townh->towns.size());
  515. f = iter->first;
  516. }
  517. return std::pair<int,int>(Obj::TOWN,f);
  518. }
  519. case Obj::RANDOM_MONSTER_L5:
  520. return std::pair<int,int>(Obj::MONSTER, VLC->creh->pickRandomMonster(boost::ref(ran), 5));
  521. case Obj::RANDOM_MONSTER_L6:
  522. return std::pair<int,int>(Obj::MONSTER, VLC->creh->pickRandomMonster(boost::ref(ran), 6));
  523. case Obj::RANDOM_MONSTER_L7:
  524. return std::pair<int,int>(Obj::MONSTER, VLC->creh->pickRandomMonster(boost::ref(ran), 7));
  525. case Obj::RANDOM_DWELLING:
  526. case Obj::RANDOM_DWELLING_LVL:
  527. case Obj::RANDOM_DWELLING_FACTION:
  528. {
  529. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  530. int faction;
  531. //if castle alignment available
  532. if (auto info = dynamic_cast<CCreGenAsCastleInfo*>(dwl->info))
  533. {
  534. faction = ran() % VLC->townh->factions.size();
  535. if (info->asCastle)
  536. {
  537. for(ui32 i=0;i<map->objects.size();i++)
  538. {
  539. if(map->objects[i]->ID==Obj::RANDOM_TOWN
  540. && dynamic_cast<CGTownInstance*>(map->objects[i].get())->identifier == info->identifier)
  541. {
  542. randomizeObject(map->objects[i]); //we have to randomize the castle first
  543. faction = map->objects[i]->subID;
  544. break;
  545. }
  546. else if(map->objects[i]->ID==Obj::TOWN
  547. && dynamic_cast<CGTownInstance*>(map->objects[i].get())->identifier == info->identifier)
  548. {
  549. faction = map->objects[i]->subID;
  550. break;
  551. }
  552. }
  553. }
  554. else
  555. {
  556. while((!(info->castles[0]&(1<<faction))))
  557. {
  558. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  559. break;
  560. faction = ran()%GameConstants::F_NUMBER;
  561. }
  562. }
  563. }
  564. else // castle alignment fixed
  565. faction = obj->subID;
  566. int level;
  567. //if level set to range
  568. if (auto info = dynamic_cast<CCreGenLeveledInfo*>(dwl->info))
  569. level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  570. else // fixed level
  571. level = obj->subID;
  572. delete dwl->info;
  573. dwl->info = nullptr;
  574. std::pair<int,int> result(-1, -1);
  575. int cid = VLC->townh->towns[faction].creatures[level][0];
  576. //golem factory is not in list of cregens but can be placed as random object
  577. static const int factoryCreatures[] = {32, 33, 116, 117};
  578. std::vector<int> factory(factoryCreatures, factoryCreatures + ARRAY_COUNT(factoryCreatures));
  579. if (vstd::contains(factory, cid))
  580. result = std::pair<int,int>(20, 1);
  581. //NOTE: this will pick last dwelling with this creature (Mantis #900)
  582. //check for block map equality is better but more complex solution
  583. BOOST_FOREACH(auto &iter, VLC->objh->cregens)
  584. if (iter.second == cid)
  585. result = std::pair<int,int>(17, iter.first);
  586. if (result.first == -1)
  587. {
  588. tlog0 << "Error: failed to find creature for dwelling of "<< int(faction) << " of level " << int(level) << "\n";
  589. auto iter = VLC->objh->cregens.begin();
  590. std::advance(iter, ran() % VLC->objh->cregens.size() );
  591. result = std::pair<int, int>(17, iter->first);
  592. }
  593. return result;
  594. }
  595. }
  596. return std::pair<int,int>(-1,-1);
  597. }
  598. void CGameState::randomizeObject(CGObjectInstance *cur)
  599. {
  600. std::pair<int,int> ran = pickObject(cur);
  601. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  602. {
  603. if(cur->ID==Obj::TOWN) //town - set def
  604. {
  605. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  606. t->town = &VLC->townh->towns[t->subID];
  607. if(t->hasCapitol())
  608. t->defInfo = VLC->dobjinfo->capitols[t->subID];
  609. else if(t->hasFort())
  610. t->defInfo = VLC->dobjinfo->gobjs[Obj::TOWN][t->subID];
  611. else
  612. t->defInfo = VLC->dobjinfo->villages[t->subID];
  613. }
  614. return;
  615. }
  616. else if(ran.first==Obj::HERO)//special code for hero
  617. {
  618. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  619. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  620. cur->ID = ran.first;
  621. h->portrait = cur->subID = ran.second;
  622. h->type = VLC->heroh->heroes[ran.second];
  623. h->randomizeArmy(h->type->heroClass->faction);
  624. map->heroes.push_back(h);
  625. return; //TODO: maybe we should do something with definfo?
  626. }
  627. else if(ran.first==Obj::TOWN)//special code for town
  628. {
  629. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  630. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  631. cur->ID = ran.first;
  632. cur->subID = ran.second;
  633. //FIXME: copy-pasted from above
  634. t->town = &VLC->townh->towns[t->subID];
  635. if(t->hasCapitol())
  636. t->defInfo = VLC->dobjinfo->capitols[t->subID];
  637. else if(t->hasFort())
  638. t->defInfo = VLC->dobjinfo->gobjs[Obj::TOWN][t->subID];
  639. else
  640. t->defInfo = VLC->dobjinfo->villages[t->subID];
  641. t->randomizeArmy(t->subID);
  642. map->towns.push_back(t);
  643. return;
  644. }
  645. //we have to replace normal random object
  646. cur->ID = ran.first;
  647. cur->subID = ran.second;
  648. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  649. map->customDefs.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  650. if(!cur->defInfo)
  651. {
  652. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  653. return;
  654. }
  655. map->addBlockVisTiles(cur);
  656. }
  657. int CGameState::getDate(int mode) const
  658. {
  659. int temp;
  660. switch (mode)
  661. {
  662. case 0: //day number
  663. return day;
  664. break;
  665. case 1: //day of week
  666. temp = (day)%7; // 1 - Monday, 7 - Sunday
  667. if (temp)
  668. return temp;
  669. else return 7;
  670. break;
  671. case 2: //current week
  672. temp = ((day-1)/7)+1;
  673. if (!(temp%4))
  674. return 4;
  675. else
  676. return (temp%4);
  677. break;
  678. case 3: //current month
  679. return ((day-1)/28)+1;
  680. break;
  681. case 4: //day of month
  682. temp = (day)%28;
  683. if (temp)
  684. return temp;
  685. else return 28;
  686. break;
  687. }
  688. return 0;
  689. }
  690. CGameState::CGameState()
  691. {
  692. gs = this;
  693. mx = new boost::shared_mutex();
  694. applierGs = new CApplier<CBaseForGSApply>;
  695. registerTypes2(*applierGs);
  696. objCaller = new CObjectCallersHandler;
  697. globalEffects.setDescription("Global effects");
  698. }
  699. CGameState::~CGameState()
  700. {
  701. //delete mx;//TODO: crash on Linux (mutex must be unlocked before destruction)
  702. map.dellNull();
  703. curB.dellNull();
  704. //delete scenarioOps; //TODO: fix for loading ind delete
  705. //delete initialOpts;
  706. delete applierGs;
  707. delete objCaller;
  708. }
  709. BattleInfo * CGameState::setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town)
  710. {
  711. const TerrainTile &t = map->getTile(tile);
  712. int terrain = t.terType;
  713. if(t.isCoastal() && !t.isWater())
  714. terrain = ETerrainType::SAND;
  715. int terType = battleGetBattlefieldType(tile);
  716. return BattleInfo::setupBattle(tile, terrain, terType, armies, heroes, creatureBank, town);
  717. }
  718. void CGameState::init(StartInfo * si)
  719. {
  720. auto giveCampaignBonusToHero = [&](CGHeroInstance * hero)
  721. {
  722. const boost::optional<CScenarioTravel::STravelBonus> & curBonus = scenarioOps->campState->getBonusForCurrentMap();
  723. if(!curBonus)
  724. return;
  725. if(curBonus->isBonusForHero())
  726. {
  727. //apply bonus
  728. switch (curBonus->type)
  729. {
  730. case CScenarioTravel::STravelBonus::SPELL:
  731. hero->spells.insert(curBonus->info2);
  732. break;
  733. case CScenarioTravel::STravelBonus::MONSTER:
  734. {
  735. for(int i=0; i<GameConstants::ARMY_SIZE; i++)
  736. {
  737. if(hero->slotEmpty(i))
  738. {
  739. hero->addToSlot(i, curBonus->info2, curBonus->info3);
  740. break;
  741. }
  742. }
  743. }
  744. break;
  745. case CScenarioTravel::STravelBonus::ARTIFACT:
  746. gs->giveHeroArtifact(hero, curBonus->info2);
  747. break;
  748. case CScenarioTravel::STravelBonus::SPELL_SCROLL:
  749. {
  750. CArtifactInstance * scroll = CArtifactInstance::createScroll(VLC->spellh->spells[curBonus->info2]);
  751. scroll->putAt(ArtifactLocation(hero, scroll->firstAvailableSlot(hero)));
  752. }
  753. break;
  754. case CScenarioTravel::STravelBonus::PRIMARY_SKILL:
  755. {
  756. const ui8* ptr = reinterpret_cast<const ui8*>(&curBonus->info2);
  757. for (int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  758. {
  759. int val = ptr[g];
  760. if (val == 0)
  761. {
  762. continue;
  763. }
  764. Bonus *bb = new Bonus(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::CAMPAIGN_BONUS, val, scenarioOps->campState->currentMap, g);
  765. hero->addNewBonus(bb);
  766. }
  767. }
  768. break;
  769. case CScenarioTravel::STravelBonus::SECONDARY_SKILL:
  770. hero->setSecSkillLevel(static_cast<CGHeroInstance::SecondarySkill>(curBonus->info2), curBonus->info3, true);
  771. break;
  772. }
  773. }
  774. };
  775. auto getHumanPlayerInfo = [&]() -> std::vector<const PlayerSettings *>
  776. {
  777. std::vector<const PlayerSettings *> ret;
  778. for(auto it = scenarioOps->playerInfos.cbegin();
  779. it != scenarioOps->playerInfos.cend(); ++it)
  780. {
  781. if(it->second.playerID != PlayerSettings::PLAYER_AI)
  782. ret.push_back(&it->second);
  783. }
  784. return ret;
  785. };
  786. auto replaceHero = [&](int objId, CGHeroInstance * ghi)
  787. {
  788. ghi->id = objId;
  789. gs->map->objects[objId] = ghi;
  790. gs->map->heroes.push_back(ghi);
  791. };
  792. tlog0 << "\tUsing random seed: "<< si->seedToBeUsed << std::endl;
  793. ran.seed((boost::int32_t)si->seedToBeUsed);
  794. scenarioOps = new StartInfo(*si);
  795. initialOpts = new StartInfo(*si);
  796. si = NULL;
  797. switch(scenarioOps->mode)
  798. {
  799. case StartInfo::NEW_GAME:
  800. {
  801. if(scenarioOps->createRandomMap)
  802. {
  803. tlog0 << "Create random map." << std::endl;
  804. //TODO random map
  805. }
  806. else
  807. {
  808. tlog0 << "Open map file: " << scenarioOps->mapname << std::endl;
  809. map = CMapService::loadMap(scenarioOps->mapname).release();
  810. }
  811. }
  812. break;
  813. case StartInfo::CAMPAIGN:
  814. {
  815. tlog0 << "Open campaign map file: " << scenarioOps->campState->currentMap << std::endl;
  816. auto campaign = scenarioOps->campState;
  817. assert(vstd::contains(campaign->camp->mapPieces, scenarioOps->campState->currentMap));
  818. std::string & mapContent = campaign->camp->mapPieces[scenarioOps->campState->currentMap];
  819. auto buffer = reinterpret_cast<const ui8 *>(mapContent.data());
  820. map = CMapService::loadMap(buffer, mapContent.size()).release();
  821. }
  822. break;
  823. case StartInfo::DUEL:
  824. initDuel();
  825. return;
  826. default:
  827. tlog1 << "Wrong mode: " << (int)scenarioOps->mode << std::endl;
  828. return;
  829. }
  830. VLC->arth->initAllowedArtifactsList(map->allowedArtifact);
  831. tlog0 << "Map loaded!" << std::endl;
  832. //tlog0 <<"Reading and detecting map file (together): "<<tmh.getDif()<<std::endl;
  833. tlog0 << "\tOur checksum for the map: "<< map->checksum << std::endl;
  834. if(scenarioOps->mapfileChecksum)
  835. {
  836. tlog0 << "\tServer checksum for " << scenarioOps->mapname <<": "<< scenarioOps->mapfileChecksum << std::endl;
  837. if(map->checksum != scenarioOps->mapfileChecksum)
  838. {
  839. tlog1 << "Wrong map checksum!!!" << std::endl;
  840. throw std::runtime_error("Wrong checksum");
  841. }
  842. }
  843. else
  844. scenarioOps->mapfileChecksum = map->checksum;
  845. day = 0;
  846. tlog4 << "Initialization:";
  847. tlog4 << "\tPicking grail position";
  848. //pick grail location
  849. if(map->grailPos.x < 0 || map->grailRadious) //grail not set or set within a radius around some place
  850. {
  851. if(!map->grailRadious) //radius not given -> anywhere on map
  852. map->grailRadious = map->width * 2;
  853. std::vector<int3> allowedPos;
  854. // add all not blocked tiles in range
  855. for (int i = 0; i < map->width ; i++)
  856. {
  857. for (int j = 0; j < map->height ; j++)
  858. {
  859. for (int k = 0; k < (map->twoLevel ? 2 : 1); k++)
  860. {
  861. const TerrainTile &t = map->terrain[i][j][k];
  862. if(!t.blocked
  863. && !t.visitable
  864. && t.terType != ETerrainType::WATER
  865. && t.terType != ETerrainType::ROCK
  866. && map->grailPos.dist2d(int3(i,j,k)) <= map->grailRadious)
  867. allowedPos.push_back(int3(i,j,k));
  868. }
  869. }
  870. }
  871. //remove tiles with holes
  872. for(ui32 no=0; no<map->objects.size(); ++no)
  873. if(map->objects[no]->ID == Obj::HOLE)
  874. allowedPos -= map->objects[no]->pos;
  875. if(allowedPos.size())
  876. map->grailPos = allowedPos[ran() % allowedPos.size()];
  877. else
  878. tlog2 << "Warning: Grail cannot be placed, no appropriate tile found!\n";
  879. }
  880. //picking random factions for players
  881. tlog4 << "\tPicking random factions for players";
  882. for(auto it = scenarioOps->playerInfos.begin();
  883. it != scenarioOps->playerInfos.end(); ++it)
  884. {
  885. if(it->second.castle==-1)
  886. {
  887. int randomID = ran() % map->players[it->first].allowedFactions.size();
  888. auto iter = map->players[it->first].allowedFactions.begin();
  889. std::advance(iter, randomID);
  890. it->second.castle = *iter;
  891. }
  892. }
  893. //randomizing objects
  894. tlog4 << "\tRandomizing objects";
  895. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  896. {
  897. randomizeObject(obj);
  898. obj->hoverName = VLC->generaltexth->names[obj->ID];
  899. //handle Favouring Winds - mark tiles under it
  900. if(obj->ID == Obj::FAVORABLE_WINDS)
  901. for (int i = 0; i < obj->getWidth() ; i++)
  902. for (int j = 0; j < obj->getHeight() ; j++)
  903. {
  904. int3 pos = obj->pos - int3(i,j,0);
  905. if(map->isInTheMap(pos))
  906. map->getTile(pos).extTileFlags |= 128;
  907. }
  908. }
  909. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  910. /*********creating players entries in gs****************************************/
  911. tlog4 << "\tCreating player entries in gs";
  912. for(auto it = scenarioOps->playerInfos.begin();
  913. it != scenarioOps->playerInfos.end(); ++it)
  914. {
  915. std::pair<TPlayerColor,PlayerState> ins(it->first,PlayerState());
  916. ins.second.color=ins.first;
  917. ins.second.human = it->second.playerID;
  918. ins.second.team = map->players[ins.first].team;
  919. teams[ins.second.team].id = ins.second.team;//init team
  920. teams[ins.second.team].players.insert(ins.first);//add player to team
  921. players.insert(ins);
  922. }
  923. /*********give starting hero****************************************/
  924. tlog4 << "\tGiving starting hero";
  925. {
  926. bool campaignGiveHero = false;
  927. if(scenarioOps->campState)
  928. {
  929. auto bonus = scenarioOps->campState->getBonusForCurrentMap();
  930. if(bonus.is_initialized())
  931. {
  932. campaignGiveHero = scenarioOps->mode == StartInfo::CAMPAIGN &&
  933. bonus.get().type == CScenarioTravel::STravelBonus::HERO;
  934. }
  935. }
  936. for(auto it = scenarioOps->playerInfos.begin(); it != scenarioOps->playerInfos.end(); ++it)
  937. {
  938. const PlayerInfo &p = map->players[it->first];
  939. bool generateHero = (p.generateHeroAtMainTown ||
  940. (it->second.playerID != PlayerSettings::PLAYER_AI && campaignGiveHero)) && p.hasMainTown;
  941. if(generateHero && vstd::contains(scenarioOps->playerInfos, it->first))
  942. {
  943. int3 hpos = p.posOfMainTown;
  944. hpos.x+=1;
  945. int h = pickHero(it->first);
  946. if(it->second.hero == -1)
  947. it->second.hero = h;
  948. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(Obj::HERO,h,hpos,it->first));
  949. nnn->id = map->objects.size();
  950. nnn->initHero();
  951. map->heroes.push_back(nnn);
  952. map->objects.push_back(nnn);
  953. map->addBlockVisTiles(nnn);
  954. }
  955. }
  956. }
  957. /*************************replace hero placeholders*****************************/
  958. tlog4 << "\tReplacing hero placeholders";
  959. if (scenarioOps->campState)
  960. {
  961. auto campaign = scenarioOps->campState;
  962. auto bonus = campaign->getBonusForCurrentMap();
  963. if(bonus.is_initialized())
  964. {
  965. std::vector<CGHeroInstance *> Xheroes;
  966. if (bonus->type == CScenarioTravel::STravelBonus::PLAYER_PREV_SCENARIO)
  967. {
  968. Xheroes = campaign->camp->scenarios[bonus->info2].crossoverHeroes;
  969. }
  970. //selecting heroes by type
  971. for(int g=0; g<map->objects.size(); ++g)
  972. {
  973. CGObjectInstance * obj = map->objects[g];
  974. if (obj->ID != Obj::HERO_PLACEHOLDER)
  975. {
  976. continue;
  977. }
  978. CGHeroPlaceholder * hp = static_cast<CGHeroPlaceholder*>(obj);
  979. if(hp->subID != 0xFF) //select by type
  980. {
  981. bool found = false;
  982. BOOST_FOREACH(CGHeroInstance * ghi, Xheroes)
  983. {
  984. if (ghi->subID == hp->subID)
  985. {
  986. found = true;
  987. replaceHero(g, ghi);
  988. Xheroes -= ghi;
  989. break;
  990. }
  991. }
  992. if (!found)
  993. {
  994. //TODO: create new hero of this type
  995. }
  996. }
  997. }
  998. //selecting heroes by power
  999. std::sort(Xheroes.begin(), Xheroes.end(), [](const CGHeroInstance * a, const CGHeroInstance * b)
  1000. {
  1001. return a->getHeroStrength() > b->getHeroStrength();
  1002. }); //sort, descending strength
  1003. for(int g=0; g<map->objects.size(); ++g)
  1004. {
  1005. CGObjectInstance * obj = map->objects[g];
  1006. if (obj->ID != Obj::HERO_PLACEHOLDER)
  1007. {
  1008. continue;
  1009. }
  1010. CGHeroPlaceholder * hp = static_cast<CGHeroPlaceholder*>(obj);
  1011. if (hp->subID == 0xFF) //select by power
  1012. {
  1013. if(Xheroes.size() > hp->power - 1)
  1014. replaceHero(g, Xheroes[hp->power - 1]);
  1015. else
  1016. tlog2 << "Warning, to hero to replace!\n";
  1017. //we don't have to remove hero from Xheroes because it would destroy the order and duplicates shouldn't happen
  1018. }
  1019. }
  1020. }
  1021. }
  1022. /******************RESOURCES****************************************************/
  1023. tlog4 << "\tSetting up resources";
  1024. const JsonNode config(ResourceID("config/startres.json"));
  1025. const JsonVector &vector = config["difficulty"].Vector();
  1026. const JsonNode &level = vector[scenarioOps->difficulty];
  1027. TResources startresAI(level["ai"]);
  1028. TResources startresHuman(level["human"]);
  1029. for (auto i = players.begin(); i!=players.end(); i++)
  1030. {
  1031. PlayerState &p = i->second;
  1032. if (p.human)
  1033. p.resources = startresHuman;
  1034. else
  1035. p.resources = startresAI;
  1036. }
  1037. //give start resource bonus in case of campaign
  1038. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1039. {
  1040. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1041. if(chosenBonus.is_initialized() && chosenBonus->type == CScenarioTravel::STravelBonus::RESOURCE)
  1042. {
  1043. std::vector<const PlayerSettings *> people = getHumanPlayerInfo(); //players we will give resource bonus
  1044. BOOST_FOREACH(const PlayerSettings *ps, people)
  1045. {
  1046. std::vector<int> res; //resources we will give
  1047. switch (chosenBonus->info1)
  1048. {
  1049. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  1050. res.push_back(chosenBonus->info1);
  1051. break;
  1052. case 0xFD: //wood+ore
  1053. res.push_back(Res::WOOD); res.push_back(Res::ORE);
  1054. break;
  1055. case 0xFE: //rare
  1056. res.push_back(Res::MERCURY); res.push_back(Res::SULFUR); res.push_back(Res::CRYSTAL); res.push_back(Res::GEMS);
  1057. break;
  1058. default:
  1059. assert(0);
  1060. break;
  1061. }
  1062. //increasing resource quantity
  1063. for (int n=0; n<res.size(); ++n)
  1064. {
  1065. players[ps->color].resources[res[n]] += chosenBonus->info2;
  1066. }
  1067. }
  1068. }
  1069. }
  1070. /*************************HEROES************************************************/
  1071. tlog4 << "\tSetting up heroes";
  1072. std::set<int> hids; //hero ids to create pool
  1073. for(ui32 i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1074. if(map->allowedHeroes[i])
  1075. hids.insert(i);
  1076. for (ui32 i=0; i<map->heroes.size();i++) //heroes instances initialization
  1077. {
  1078. if (map->heroes[i]->getOwner()<0)
  1079. {
  1080. tlog2 << "Warning - hero with uninitialized owner!\n";
  1081. continue;
  1082. }
  1083. CGHeroInstance * vhi = (map->heroes[i]);
  1084. vhi->initHero();
  1085. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1086. hids.erase(vhi->subID);
  1087. }
  1088. for (ui32 i=0; i<map->objects.size();i++) //prisons
  1089. {
  1090. if (map->objects[i]->ID == Obj::PRISON)
  1091. hids.erase(map->objects[i]->subID);
  1092. }
  1093. for(ui32 i=0; i<map->predefinedHeroes.size(); i++)
  1094. {
  1095. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1096. continue;
  1097. map->predefinedHeroes[i]->initHero();
  1098. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1099. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1100. hids.erase(map->predefinedHeroes[i]->subID);
  1101. }
  1102. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go with default state into the pool
  1103. {
  1104. CGHeroInstance * vhi = new CGHeroInstance();
  1105. vhi->initHero(hid);
  1106. hpool.heroesPool[hid] = vhi;
  1107. hpool.pavailable[hid] = 0xff;
  1108. }
  1109. for(ui32 i=0; i<map->disposedHeroes.size(); i++)
  1110. {
  1111. hpool.pavailable[map->disposedHeroes[i].heroId] = map->disposedHeroes[i].players;
  1112. }
  1113. if (scenarioOps->mode == StartInfo::CAMPAIGN) //give campaign bonuses for specific / best hero
  1114. {
  1115. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1116. if (chosenBonus.is_initialized() && chosenBonus->isBonusForHero() && chosenBonus->info1 != 0xFFFE) //exclude generated heroes
  1117. {
  1118. //find human player
  1119. int humanPlayer=GameConstants::NEUTRAL_PLAYER;
  1120. for (auto it=players.begin(); it != players.end(); ++it)
  1121. {
  1122. if(it->second.human)
  1123. {
  1124. humanPlayer = it->first;
  1125. break;
  1126. }
  1127. }
  1128. assert(humanPlayer != GameConstants::NEUTRAL_PLAYER);
  1129. std::vector<ConstTransitivePtr<CGHeroInstance> > & heroes = players[humanPlayer].heroes;
  1130. if (chosenBonus->info1 == 0xFFFD) //most powerful
  1131. {
  1132. int maxB = -1;
  1133. for (int b=0; b<heroes.size(); ++b)
  1134. {
  1135. if (maxB == -1 || heroes[b]->getTotalStrength() > heroes[maxB]->getTotalStrength())
  1136. {
  1137. maxB = b;
  1138. }
  1139. }
  1140. if(maxB < 0)
  1141. tlog2 << "Warning - cannot give bonus to hero cause there are no heroes!\n";
  1142. else
  1143. giveCampaignBonusToHero(heroes[maxB]);
  1144. }
  1145. else //specific hero
  1146. {
  1147. for (int b=0; b<heroes.size(); ++b)
  1148. {
  1149. if (heroes[b]->subID == chosenBonus->info1)
  1150. {
  1151. giveCampaignBonusToHero(heroes[b]);
  1152. break;
  1153. }
  1154. }
  1155. }
  1156. }
  1157. }
  1158. /*************************FOG**OF**WAR******************************************/
  1159. tlog4 << "\tFog of war";
  1160. for(auto k=teams.begin(); k!=teams.end(); ++k)
  1161. {
  1162. k->second.fogOfWarMap.resize(map->width);
  1163. for(int g=0; g<map->width; ++g)
  1164. k->second.fogOfWarMap[g].resize(map->height);
  1165. for(int g=-0; g<map->width; ++g)
  1166. for(int h=0; h<map->height; ++h)
  1167. k->second.fogOfWarMap[g][h].resize(map->twoLevel ? 2 : 1, 0);
  1168. for(int g=0; g<map->width; ++g)
  1169. for(int h=0; h<map->height; ++h)
  1170. for(int v = 0; v < (map->twoLevel ? 2 : 1); ++v)
  1171. k->second.fogOfWarMap[g][h][v] = 0;
  1172. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1173. {
  1174. if( !vstd::contains(k->second.players, obj->tempOwner)) continue; //not a flagged object
  1175. boost::unordered_set<int3, ShashInt3> tiles;
  1176. obj->getSightTiles(tiles);
  1177. BOOST_FOREACH(int3 tile, tiles)
  1178. {
  1179. k->second.fogOfWarMap[tile.x][tile.y][tile.z] = 1;
  1180. }
  1181. }
  1182. }
  1183. tlog4 << "\tStarting bonuses";
  1184. for(auto k=players.begin(); k!=players.end(); ++k)
  1185. {
  1186. //starting bonus
  1187. if(scenarioOps->playerInfos[k->first].bonus==PlayerSettings::RANDOM)
  1188. scenarioOps->playerInfos[k->first].bonus = ran()%3;
  1189. switch(scenarioOps->playerInfos[k->first].bonus)
  1190. {
  1191. case PlayerSettings::GOLD:
  1192. k->second.resources[Res::GOLD] += 500 + (ran()%6)*100;
  1193. break;
  1194. case PlayerSettings::RESOURCE:
  1195. {
  1196. int res = VLC->townh->towns[scenarioOps->playerInfos[k->first].castle].primaryRes;
  1197. if(res == 127)
  1198. {
  1199. k->second.resources[Res::WOOD] += 5 + ran()%6;
  1200. k->second.resources[Res::ORE] += 5 + ran()%6;
  1201. }
  1202. else
  1203. {
  1204. k->second.resources[res] += 3 + ran()%4;
  1205. }
  1206. break;
  1207. }
  1208. case PlayerSettings::ARTIFACT:
  1209. {
  1210. if(!k->second.heroes.size())
  1211. {
  1212. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1213. break;
  1214. }
  1215. CArtifact *toGive;
  1216. toGive = VLC->arth->artifacts[VLC->arth->getRandomArt (CArtifact::ART_TREASURE)];
  1217. CGHeroInstance *hero = k->second.heroes[0];
  1218. giveHeroArtifact(hero, toGive->id);
  1219. }
  1220. break;
  1221. }
  1222. }
  1223. /****************************TOWNS************************************************/
  1224. tlog4 << "\tTowns";
  1225. CGTownInstance::universitySkills.clear();
  1226. for ( int i=0; i<4; i++)
  1227. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  1228. for (ui32 i=0;i<map->towns.size();i++)
  1229. {
  1230. CGTownInstance * vti =(map->towns[i]);
  1231. if(!vti->town)
  1232. vti->town = &VLC->townh->towns[vti->subID];
  1233. if (vti->name.length()==0) // if town hasn't name we draw it
  1234. vti->name = vti->town->names[ran()%vti->town->names.size()];
  1235. //init buildings
  1236. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1237. {
  1238. vti->builtBuildings.erase(-50);
  1239. vti->builtBuildings.insert(EBuilding::VILLAGE_HALL);
  1240. vti->builtBuildings.insert(EBuilding::TAVERN);
  1241. vti->builtBuildings.insert(EBuilding::DWELL_FIRST);
  1242. if(ran()%2)
  1243. vti->builtBuildings.insert(EBuilding::DWELL_FIRST+1);
  1244. }
  1245. if (vstd::contains(vti->builtBuildings, EBuilding::SHIPYARD) && vti->state()==IBoatGenerator::TILE_BLOCKED)
  1246. vti->builtBuildings.erase(EBuilding::SHIPYARD);//if we have harbor without water - erase it (this is H3 behaviour)
  1247. //init hordes
  1248. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1249. if (vstd::contains(vti->builtBuildings,(-31-i))) //if we have horde for this level
  1250. {
  1251. vti->builtBuildings.erase(-31-i);//remove old ID
  1252. if (vti->town->hordeLvl[0] == i)//if town first horde is this one
  1253. {
  1254. vti->builtBuildings.insert(EBuilding::HORDE_1);//add it
  1255. if (vstd::contains(vti->builtBuildings,(EBuilding::DWELL_UP_FIRST+i)))//if we have upgraded dwelling as well
  1256. vti->builtBuildings.insert(EBuilding::HORDE_1_UPGR);//add it as well
  1257. }
  1258. if (vti->town->hordeLvl[1] == i)//if town second horde is this one
  1259. {
  1260. vti->builtBuildings.insert(EBuilding::HORDE_2);
  1261. if (vstd::contains(vti->builtBuildings,(EBuilding::DWELL_UP_FIRST+i)))
  1262. vti->builtBuildings.insert(EBuilding::HORDE_2_UPGR);
  1263. }
  1264. }
  1265. //town events
  1266. BOOST_FOREACH(CCastleEvent *ev, vti->events)
  1267. {
  1268. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1269. if (vstd::contains(ev->buildings,(-31-i))) //if we have horde for this level
  1270. {
  1271. ev->buildings.erase(-31-i);
  1272. if (vti->town->hordeLvl[0] == i)
  1273. ev->buildings.insert(EBuilding::HORDE_1);
  1274. if (vti->town->hordeLvl[1] == i)
  1275. ev->buildings.insert(EBuilding::HORDE_2);
  1276. }
  1277. }
  1278. //init spells
  1279. vti->spells.resize(GameConstants::SPELL_LEVELS);
  1280. CSpell *s;
  1281. for(ui32 z=0; z<vti->obligatorySpells.size();z++)
  1282. {
  1283. s = VLC->spellh->spells[vti->obligatorySpells[z]];
  1284. vti->spells[s->level-1].push_back(s->id);
  1285. vti->possibleSpells -= s->id;
  1286. }
  1287. while(vti->possibleSpells.size())
  1288. {
  1289. ui32 total=0;
  1290. int sel = -1;
  1291. for(ui32 ps=0;ps<vti->possibleSpells.size();ps++)
  1292. total += VLC->spellh->spells[vti->possibleSpells[ps]]->probabilities[vti->subID];
  1293. if (total == 0) // remaining spells have 0 probability
  1294. break;
  1295. int r = ran()%total;
  1296. for(ui32 ps=0; ps<vti->possibleSpells.size();ps++)
  1297. {
  1298. r -= VLC->spellh->spells[vti->possibleSpells[ps]]->probabilities[vti->subID];
  1299. if(r<0)
  1300. {
  1301. sel = ps;
  1302. break;
  1303. }
  1304. }
  1305. if(sel<0)
  1306. sel=0;
  1307. CSpell *s = VLC->spellh->spells[vti->possibleSpells[sel]];
  1308. vti->spells[s->level-1].push_back(s->id);
  1309. vti->possibleSpells -= s->id;
  1310. }
  1311. vti->possibleSpells.clear();
  1312. if(vti->getOwner() != 255)
  1313. getPlayer(vti->getOwner())->towns.push_back(vti);
  1314. }
  1315. //campaign bonuses for towns
  1316. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1317. {
  1318. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1319. if (chosenBonus.is_initialized() && chosenBonus->type == CScenarioTravel::STravelBonus::BUILDING)
  1320. {
  1321. for (int g=0; g<map->towns.size(); ++g)
  1322. {
  1323. PlayerState * owner = getPlayer(map->towns[g]->getOwner());
  1324. if (owner)
  1325. {
  1326. PlayerInfo & pi = map->players[owner->color];
  1327. if (owner->human && //human-owned
  1328. map->towns[g]->pos == pi.posOfMainTown + int3(2, 0, 0))
  1329. {
  1330. map->towns[g]->builtBuildings.insert(
  1331. CBuildingHandler::campToERMU(chosenBonus->info1, map->towns[g]->town->typeID, map->towns[g]->builtBuildings));
  1332. break;
  1333. }
  1334. }
  1335. }
  1336. }
  1337. }
  1338. tlog4 << "\tObject initialization";
  1339. objCaller->preInit();
  1340. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1341. {
  1342. obj->initObj();
  1343. if(obj->ID == Obj::PRISON) //prison also needs to initialize hero
  1344. static_cast<CGHeroInstance*>(obj)->initHero();
  1345. }
  1346. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1347. {
  1348. switch (obj->ID)
  1349. {
  1350. case Obj::QUEST_GUARD:
  1351. case Obj::SEER_HUT:
  1352. {
  1353. auto q = static_cast<CGSeerHut*>(obj);
  1354. assert (q);
  1355. q->setObjToKill();
  1356. }
  1357. }
  1358. }
  1359. CGTeleport::postInit(); //pairing subterranean gates
  1360. buildBonusSystemTree();
  1361. for(auto k=players.begin(); k!=players.end(); ++k)
  1362. {
  1363. if(k->first==255)
  1364. continue;
  1365. //init visiting and garrisoned heroes
  1366. BOOST_FOREACH(CGHeroInstance *h, k->second.heroes)
  1367. {
  1368. BOOST_FOREACH(CGTownInstance *t, k->second.towns)
  1369. {
  1370. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1371. if(vistile == h->pos || h->pos==t->pos)
  1372. {
  1373. t->setVisitingHero(h);
  1374. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1375. {
  1376. map->removeBlockVisTiles(h);
  1377. h->pos.x -= 1;
  1378. map->addBlockVisTiles(h);
  1379. }
  1380. break;
  1381. }
  1382. }
  1383. }
  1384. }
  1385. tlog4 << "\tChecking objectives";
  1386. map->checkForObjectives(); //needs to be run when all objects are properly placed
  1387. int seedAfterInit = ran();
  1388. tlog0 << "Seed after init is " << seedAfterInit << " (before was " << scenarioOps->seedToBeUsed << ")" << std::endl;
  1389. if(scenarioOps->seedPostInit > 0)
  1390. {
  1391. //RNG must be in the same state on all machines when initialization is done (otherwise we have desync)
  1392. assert(scenarioOps->seedPostInit == seedAfterInit);
  1393. }
  1394. else
  1395. {
  1396. scenarioOps->seedPostInit = seedAfterInit; //store the post init "seed"
  1397. }
  1398. }
  1399. void CGameState::initDuel()
  1400. {
  1401. DuelParameters dp;
  1402. try //CLoadFile likes throwing
  1403. {
  1404. if(boost::algorithm::ends_with(scenarioOps->mapname, ".json"))
  1405. {
  1406. tlog0 << "Loading duel settings from JSON file: " << scenarioOps->mapname << std::endl;
  1407. dp = DuelParameters::fromJSON(scenarioOps->mapname);
  1408. tlog0 << "JSON file has been successfully read!\n";
  1409. }
  1410. else
  1411. {
  1412. CLoadFile lf(scenarioOps->mapname);
  1413. lf >> dp;
  1414. }
  1415. }
  1416. catch(...)
  1417. {
  1418. tlog1 << "Cannot load duel settings from " << scenarioOps->mapname << std::endl;
  1419. throw;
  1420. }
  1421. const CArmedInstance *armies[2] = {0};
  1422. const CGHeroInstance *heroes[2] = {0};
  1423. CGTownInstance *town = NULL;
  1424. for(int i = 0; i < 2; i++)
  1425. {
  1426. CArmedInstance *obj = NULL;
  1427. if(dp.sides[i].heroId >= 0)
  1428. {
  1429. const DuelParameters::SideSettings &ss = dp.sides[i];
  1430. CGHeroInstance *h = new CGHeroInstance();
  1431. armies[i] = heroes[i] = h;
  1432. obj = h;
  1433. h->subID = ss.heroId;
  1434. for(int i = 0; i < ss.heroPrimSkills.size(); i++)
  1435. h->pushPrimSkill(i, ss.heroPrimSkills[i]);
  1436. if(ss.spells.size())
  1437. {
  1438. h->putArtifact(ArtifactPosition::SPELLBOOK, CArtifactInstance::createNewArtifactInstance(0));
  1439. boost::copy(ss.spells, std::inserter(h->spells, h->spells.begin()));
  1440. }
  1441. BOOST_FOREACH(auto &parka, ss.artifacts)
  1442. {
  1443. h->putArtifact(parka.first, parka.second);
  1444. }
  1445. typedef const std::pair<si32, si8> &TSecSKill;
  1446. BOOST_FOREACH(TSecSKill secSkill, ss.heroSecSkills)
  1447. h->setSecSkillLevel((CGHeroInstance::SecondarySkill)secSkill.first, secSkill.second, 1);
  1448. h->initHero(h->subID);
  1449. obj->initObj();
  1450. }
  1451. else
  1452. {
  1453. CGCreature *c = new CGCreature();
  1454. armies[i] = obj = c;
  1455. //c->subID = 34;
  1456. }
  1457. obj->setOwner(i);
  1458. for(int j = 0; j < ARRAY_COUNT(dp.sides[i].stacks); j++)
  1459. {
  1460. TCreature cre = dp.sides[i].stacks[j].type;
  1461. TQuantity count = dp.sides[i].stacks[j].count;
  1462. if(count || obj->hasStackAtSlot(j))
  1463. obj->setCreature(j, cre, count);
  1464. }
  1465. BOOST_FOREACH(const DuelParameters::CusomCreature &cc, dp.creatures)
  1466. {
  1467. CCreature *c = VLC->creh->creatures[cc.id];
  1468. if(cc.attack >= 0)
  1469. c->getBonusLocalFirst(Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK))->val = cc.attack;
  1470. if(cc.defense >= 0)
  1471. c->getBonusLocalFirst(Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE))->val = cc.defense;
  1472. if(cc.speed >= 0)
  1473. c->getBonusLocalFirst(Selector::type(Bonus::STACKS_SPEED))->val = cc.speed;
  1474. if(cc.HP >= 0)
  1475. c->getBonusLocalFirst(Selector::type(Bonus::STACK_HEALTH))->val = cc.HP;
  1476. if(cc.dmg >= 0)
  1477. {
  1478. c->getBonusLocalFirst(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1))->val = cc.dmg;
  1479. c->getBonusLocalFirst(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2))->val = cc.dmg;
  1480. }
  1481. if(cc.shoots >= 0)
  1482. c->getBonusLocalFirst(Selector::type(Bonus::SHOTS))->val = cc.shoots;
  1483. }
  1484. }
  1485. curB = BattleInfo::setupBattle(int3(), dp.bfieldType, dp.terType, armies, heroes, false, town);
  1486. curB->obstacles = dp.obstacles;
  1487. curB->localInit();
  1488. return;
  1489. }
  1490. int CGameState::battleGetBattlefieldType(int3 tile) const
  1491. {
  1492. if(tile==int3() && curB)
  1493. tile = curB->tile;
  1494. else if(tile==int3() && !curB)
  1495. return -1;
  1496. const TerrainTile &t = map->getTile(tile);
  1497. //fight in mine -> subterranean
  1498. if(dynamic_cast<const CGMine *>(t.visitableObjects.front()))
  1499. return 12;
  1500. BOOST_FOREACH(auto &obj, map->objects)
  1501. {
  1502. //look only for objects covering given tile
  1503. if( !obj || obj->pos.z != tile.z
  1504. || !obj->coveringAt(tile.x - obj->pos.x, tile.y - obj->pos.y))
  1505. continue;
  1506. switch(obj->ID)
  1507. {
  1508. case Obj::CLOVER_FIELD:
  1509. return 19;
  1510. case Obj::CURSED_GROUND1: case Obj::CURSED_GROUND2:
  1511. return 22;
  1512. case Obj::EVIL_FOG:
  1513. return 20;
  1514. case Obj::FAVORABLE_WINDS:
  1515. return 21;
  1516. case Obj::FIERY_FIELDS:
  1517. return 14;
  1518. case Obj::HOLY_GROUNDS:
  1519. return 18;
  1520. case Obj::LUCID_POOLS:
  1521. return 17;
  1522. case Obj::MAGIC_CLOUDS:
  1523. return 16;
  1524. case Obj::MAGIC_PLAINS1: case Obj::MAGIC_PLAINS2:
  1525. return 9;
  1526. case Obj::ROCKLANDS:
  1527. return 15;
  1528. }
  1529. }
  1530. if(!t.isWater() && t.isCoastal())
  1531. return 1; //sand/beach
  1532. switch(t.terType)
  1533. {
  1534. case ETerrainType::DIRT:
  1535. return rand()%3+3;
  1536. case ETerrainType::SAND:
  1537. return 2; //TODO: coast support
  1538. case ETerrainType::GRASS:
  1539. return rand()%2+6;
  1540. case ETerrainType::SNOW:
  1541. return rand()%2+10;
  1542. case ETerrainType::SWAMP:
  1543. return 13;
  1544. case ETerrainType::ROUGH:
  1545. return 23;
  1546. case ETerrainType::SUBTERRANEAN:
  1547. return 12;
  1548. case ETerrainType::LAVA:
  1549. return 8;
  1550. case ETerrainType::WATER:
  1551. return 25;
  1552. case ETerrainType::ROCK:
  1553. return 15;
  1554. default:
  1555. return -1;
  1556. }
  1557. }
  1558. UpgradeInfo CGameState::getUpgradeInfo(const CStackInstance &stack)
  1559. {
  1560. UpgradeInfo ret;
  1561. const CCreature *base = stack.type;
  1562. const CGHeroInstance *h = stack.armyObj->ID == Obj::HERO ? static_cast<const CGHeroInstance*>(stack.armyObj) : NULL;
  1563. const CGTownInstance *t = NULL;
  1564. if(stack.armyObj->ID == Obj::TOWN)
  1565. t = static_cast<const CGTownInstance *>(stack.armyObj);
  1566. else if(h)
  1567. { //hero speciality
  1568. TBonusListPtr lista = h->speciality.getBonuses(Selector::typeSubtype(Bonus::SPECIAL_UPGRADE, base->idNumber));
  1569. BOOST_FOREACH(const Bonus *it, *lista)
  1570. {
  1571. ui16 nid = it->additionalInfo;
  1572. if (nid != base->idNumber) //in very specific case the upgrade is available by default (?)
  1573. {
  1574. ret.newID.push_back(nid);
  1575. ret.cost.push_back(VLC->creh->creatures[nid]->cost - base->cost);
  1576. }
  1577. }
  1578. t = h->visitedTown;
  1579. }
  1580. if(t)
  1581. {
  1582. BOOST_FOREACH(const CGTownInstance::TCreaturesSet::value_type & dwelling, t->creatures)
  1583. {
  1584. if (vstd::contains(dwelling.second, base->idNumber)) //Dwelling with our creature
  1585. {
  1586. BOOST_FOREACH(ui32 upgrID, dwelling.second)
  1587. {
  1588. if(vstd::contains(base->upgrades, upgrID)) //possible upgrade
  1589. {
  1590. ret.newID.push_back(upgrID);
  1591. ret.cost.push_back(VLC->creh->creatures[upgrID]->cost - base->cost);
  1592. }
  1593. }
  1594. }
  1595. }
  1596. }
  1597. //hero is visiting Hill Fort
  1598. if(h && map->getTile(h->visitablePos()).visitableObjects.front()->ID == 35)
  1599. {
  1600. static const int costModifiers[] = {0, 25, 50, 75, 100}; //we get cheaper upgrades depending on level
  1601. const int costModifier = costModifiers[std::min<int>(std::max((int)base->level - 1, 0), ARRAY_COUNT(costModifiers) - 1)];
  1602. BOOST_FOREACH(si32 nid, base->upgrades)
  1603. {
  1604. ret.newID.push_back(nid);
  1605. ret.cost.push_back((VLC->creh->creatures[nid]->cost - base->cost) * costModifier / 100);
  1606. }
  1607. }
  1608. if(ret.newID.size())
  1609. ret.oldID = base->idNumber;
  1610. return ret;
  1611. }
  1612. int CGameState::getPlayerRelations( ui8 color1, ui8 color2 )
  1613. {
  1614. if ( color1 == color2 )
  1615. return 2;
  1616. if(color1 == 255 || color2 == 255) //neutral player has no friends
  1617. return 0;
  1618. const TeamState * ts = getPlayerTeam(color1);
  1619. if (ts && vstd::contains(ts->players, color2))
  1620. return 1;
  1621. return 0;
  1622. }
  1623. void CGameState::getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing)
  1624. {
  1625. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1626. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1627. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1628. {
  1629. const int3 hlp = tile + dirs[i];
  1630. if(!map->isInTheMap(hlp))
  1631. continue;
  1632. const TerrainTile &hlpt = map->getTile(hlp);
  1633. // //we cannot visit things from blocked tiles
  1634. // if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  1635. // {
  1636. // continue;
  1637. // }
  1638. if(srct.terType == ETerrainType::WATER && limitCoastSailing && hlpt.terType == ETerrainType::WATER && dirs[i].x && dirs[i].y) //diagonal move through water
  1639. {
  1640. int3 hlp1 = tile,
  1641. hlp2 = tile;
  1642. hlp1.x += dirs[i].x;
  1643. hlp2.y += dirs[i].y;
  1644. if(map->getTile(hlp1).terType != ETerrainType::WATER || map->getTile(hlp2).terType != ETerrainType::WATER)
  1645. continue;
  1646. }
  1647. if((indeterminate(onLand) || onLand == (hlpt.terType!=ETerrainType::WATER) )
  1648. && hlpt.terType != ETerrainType::ROCK)
  1649. {
  1650. vec.push_back(hlp);
  1651. }
  1652. }
  1653. }
  1654. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  1655. {
  1656. if(src == dest) //same tile
  1657. return 0;
  1658. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1659. &d = map->terrain[dest.x][dest.y][dest.z];
  1660. //get basic cost
  1661. int ret = h->getTileCost(d,s);
  1662. if(d.blocked && h->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  1663. {
  1664. bool freeFlying = h->getBonusesCount(Selector::typeSubtype(Bonus::FLYING_MOVEMENT, 1)) > 0;
  1665. if(!freeFlying)
  1666. {
  1667. ret *= 1.4; //40% penalty for movement over blocked tile
  1668. }
  1669. }
  1670. else if (d.terType == ETerrainType::WATER)
  1671. {
  1672. if(h->boat && s.hasFavourableWinds() && d.hasFavourableWinds()) //Favourable Winds
  1673. ret *= 0.666;
  1674. else if (!h->boat && h->getBonusesCount(Selector::typeSubtype(Bonus::WATER_WALKING, 1)) > 0)
  1675. ret *= 1.4; //40% penalty for water walking
  1676. }
  1677. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1678. {
  1679. int old = ret;
  1680. ret *= 1.414213;
  1681. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1682. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1683. {
  1684. return remainingMovePoints;
  1685. }
  1686. }
  1687. int left = remainingMovePoints-ret;
  1688. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1689. {
  1690. std::vector<int3> vec;
  1691. getNeighbours(d, dest, vec, s.terType != ETerrainType::WATER, true);
  1692. for(size_t i=0; i < vec.size(); i++)
  1693. {
  1694. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1695. if(fcost <= left)
  1696. {
  1697. return ret;
  1698. }
  1699. }
  1700. ret = remainingMovePoints;
  1701. }
  1702. return ret;
  1703. }
  1704. void CGameState::apply(CPack *pack)
  1705. {
  1706. ui16 typ = typeList.getTypeID(pack);
  1707. applierGs->apps[typ]->applyOnGS(this,pack);
  1708. }
  1709. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1710. {
  1711. //the old pathfinder is not supported anymore!
  1712. assert(0);
  1713. return false;
  1714. }
  1715. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  1716. {
  1717. CPathfinder pathfinder(out, this, hero);
  1718. pathfinder.calculatePaths(src, movement);
  1719. }
  1720. /**
  1721. * Tells if the tile is guarded by a monster as well as the position
  1722. * of the monster that will attack on it.
  1723. *
  1724. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  1725. * the monster guarding the tile.
  1726. */
  1727. std::vector<CGObjectInstance*> CGameState::guardingCreatures (int3 pos) const
  1728. {
  1729. std::vector<CGObjectInstance*> guards;
  1730. const int3 originalPos = pos;
  1731. if (!map->isInTheMap(pos))
  1732. return guards;
  1733. const TerrainTile &posTile = map->terrain[pos.x][pos.y][pos.z];
  1734. if (posTile.visitable)
  1735. {
  1736. BOOST_FOREACH (CGObjectInstance* obj, posTile.visitableObjects)
  1737. {
  1738. if(obj->blockVisit)
  1739. {
  1740. if (obj->ID == 54) // Monster
  1741. guards.push_back(obj);
  1742. }
  1743. }
  1744. }
  1745. pos -= int3(1, 1, 0); // Start with top left.
  1746. for (int dx = 0; dx < 3; dx++)
  1747. {
  1748. for (int dy = 0; dy < 3; dy++)
  1749. {
  1750. if (map->isInTheMap(pos))
  1751. {
  1752. TerrainTile &tile = map->terrain[pos.x][pos.y][pos.z];
  1753. if (tile.visitable && (tile.terType == ETerrainType::WATER) == (posTile.terType == ETerrainType::WATER))
  1754. {
  1755. BOOST_FOREACH (CGObjectInstance* obj, tile.visitableObjects)
  1756. {
  1757. if (obj->ID == 54 && checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1758. {
  1759. guards.push_back(obj);
  1760. }
  1761. }
  1762. }
  1763. }
  1764. pos.y++;
  1765. }
  1766. pos.y -= 3;
  1767. pos.x++;
  1768. }
  1769. return guards;
  1770. }
  1771. int3 CGameState::guardingCreaturePosition (int3 pos) const
  1772. {
  1773. const int3 originalPos = pos;
  1774. // Give monster at position priority.
  1775. if (!map->isInTheMap(pos))
  1776. return int3(-1, -1, -1);
  1777. const TerrainTile &posTile = map->terrain[pos.x][pos.y][pos.z];
  1778. if (posTile.visitable)
  1779. {
  1780. BOOST_FOREACH (CGObjectInstance* obj, posTile.visitableObjects)
  1781. {
  1782. if(obj->blockVisit)
  1783. {
  1784. if (obj->ID == 54) // Monster
  1785. return pos;
  1786. else
  1787. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  1788. }
  1789. }
  1790. }
  1791. // See if there are any monsters adjacent.
  1792. pos -= int3(1, 1, 0); // Start with top left.
  1793. for (int dx = 0; dx < 3; dx++)
  1794. {
  1795. for (int dy = 0; dy < 3; dy++)
  1796. {
  1797. if (map->isInTheMap(pos))
  1798. {
  1799. TerrainTile &tile = map->terrain[pos.x][pos.y][pos.z];
  1800. if (tile.visitable && (tile.terType == ETerrainType::WATER) == (posTile.terType == ETerrainType::WATER))
  1801. {
  1802. BOOST_FOREACH (CGObjectInstance* obj, tile.visitableObjects)
  1803. {
  1804. if (obj->ID == 54 && checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1805. {
  1806. return pos;
  1807. }
  1808. }
  1809. }
  1810. }
  1811. pos.y++;
  1812. }
  1813. pos.y -= 3;
  1814. pos.x++;
  1815. }
  1816. return int3(-1, -1, -1);
  1817. }
  1818. bool CGameState::isVisible(int3 pos, int player)
  1819. {
  1820. if(player == 255) //neutral player
  1821. return false;
  1822. return getPlayerTeam(player)->fogOfWarMap[pos.x][pos.y][pos.z];
  1823. }
  1824. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  1825. {
  1826. if(player == -1)
  1827. return true;
  1828. if(player == 255) //neutral player -> TODO ??? needed?
  1829. return false;
  1830. //object is visible when at least one blocked tile is visible
  1831. for(int fx=0; fx<8; ++fx)
  1832. {
  1833. for(int fy=0; fy<6; ++fy)
  1834. {
  1835. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  1836. if(map->isInTheMap(pos)
  1837. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  1838. && isVisible(pos, player) )
  1839. return true;
  1840. }
  1841. }
  1842. return false;
  1843. }
  1844. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1845. {
  1846. const TerrainTile * pom = &map->getTile(dst);
  1847. return checkForVisitableDir(src, pom, dst);
  1848. }
  1849. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  1850. {
  1851. for(ui32 b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  1852. {
  1853. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  1854. continue;
  1855. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  1856. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  1857. {
  1858. return false;
  1859. }
  1860. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  1861. {
  1862. return false;
  1863. }
  1864. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  1865. {
  1866. return false;
  1867. }
  1868. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  1869. {
  1870. return false;
  1871. }
  1872. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  1873. {
  1874. return false;
  1875. }
  1876. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  1877. {
  1878. return false;
  1879. }
  1880. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  1881. {
  1882. return false;
  1883. }
  1884. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  1885. {
  1886. return false;
  1887. }
  1888. }
  1889. return true;
  1890. }
  1891. int CGameState::victoryCheck( ui8 player ) const
  1892. {
  1893. const PlayerState *p = CGameInfoCallback::getPlayer(player);
  1894. if(map->victoryCondition.condition == EVictoryConditionType::WINSTANDARD || map->victoryCondition.allowNormalVictory
  1895. || (!p->human && !map->victoryCondition.appliesToAI)) //if the special victory condition applies only to human, AI has the standard)
  1896. {
  1897. if(player == checkForStandardWin())
  1898. return -1;
  1899. }
  1900. if (p->enteredWinningCheatCode)
  1901. { //cheater or tester, but has entered the code...
  1902. if(map->victoryCondition.condition == EVictoryConditionType::WINSTANDARD)
  1903. return -1;
  1904. else
  1905. return 1;
  1906. }
  1907. if(p->human || map->victoryCondition.appliesToAI)
  1908. {
  1909. switch(map->victoryCondition.condition)
  1910. {
  1911. case EVictoryConditionType::ARTIFACT:
  1912. //check if any hero has winning artifact
  1913. for(size_t i = 0; i < p->heroes.size(); i++)
  1914. if(p->heroes[i]->hasArt(map->victoryCondition.objectId))
  1915. return 1;
  1916. break;
  1917. case EVictoryConditionType::GATHERTROOP:
  1918. {
  1919. //check if in players armies there is enough creatures
  1920. int total = 0; //creature counter
  1921. for(size_t i = 0; i < map->objects.size(); i++)
  1922. {
  1923. const CArmedInstance *ai = NULL;
  1924. if(map->objects[i]
  1925. && map->objects[i]->tempOwner == player //object controlled by player
  1926. && (ai = dynamic_cast<const CArmedInstance*>(map->objects[i].get()))) //contains army
  1927. {
  1928. for(TSlots::const_iterator i=ai->Slots().begin(); i!=ai->Slots().end(); ++i) //iterate through army
  1929. if(i->second->type->idNumber == map->victoryCondition.objectId) //it's searched creature
  1930. total += i->second->count;
  1931. }
  1932. }
  1933. if(total >= map->victoryCondition.count)
  1934. return 1;
  1935. }
  1936. break;
  1937. case EVictoryConditionType::GATHERRESOURCE:
  1938. if(p->resources[map->victoryCondition.objectId] >= map->victoryCondition.count)
  1939. return 1;
  1940. break;
  1941. case EVictoryConditionType::BUILDCITY:
  1942. {
  1943. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  1944. if(t->tempOwner == player && t->fortLevel()-1 >= map->victoryCondition.objectId && t->hallLevel()-1 >= map->victoryCondition.count)
  1945. return 1;
  1946. }
  1947. break;
  1948. case EVictoryConditionType::BUILDGRAIL:
  1949. BOOST_FOREACH(const CGTownInstance *t, map->towns)
  1950. if((t == map->victoryCondition.obj || !map->victoryCondition.obj)
  1951. && t->tempOwner == player
  1952. && t->hasBuilt(EBuilding::GRAIL))
  1953. return 1;
  1954. break;
  1955. case EVictoryConditionType::BEATHERO:
  1956. if(map->victoryCondition.obj->tempOwner >= GameConstants::PLAYER_LIMIT) //target hero not present on map
  1957. return 1;
  1958. break;
  1959. case EVictoryConditionType::CAPTURECITY:
  1960. {
  1961. if(map->victoryCondition.obj->tempOwner == player)
  1962. return 1;
  1963. }
  1964. break;
  1965. case EVictoryConditionType::BEATMONSTER:
  1966. if(!map->objects[map->victoryCondition.obj->id]) //target monster not present on map
  1967. return 1;
  1968. break;
  1969. case EVictoryConditionType::TAKEDWELLINGS:
  1970. for(size_t i = 0; i < map->objects.size(); i++)
  1971. {
  1972. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  1973. {
  1974. switch(map->objects[i]->ID)
  1975. {
  1976. case 17: case 18: case 19: case 20: //dwellings
  1977. case 216: case 217: case 218:
  1978. return 0; //found not flagged dwelling - player not won
  1979. }
  1980. }
  1981. }
  1982. return 1;
  1983. break;
  1984. case EVictoryConditionType::TAKEMINES:
  1985. for(size_t i = 0; i < map->objects.size(); i++)
  1986. {
  1987. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  1988. {
  1989. switch(map->objects[i]->ID)
  1990. {
  1991. case 53: case 220:
  1992. return 0; //found not flagged mine - player not won
  1993. }
  1994. }
  1995. }
  1996. return 1;
  1997. break;
  1998. case EVictoryConditionType::TRANSPORTITEM:
  1999. {
  2000. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  2001. if((t->visitingHero && t->visitingHero->hasArt(map->victoryCondition.objectId))
  2002. || (t->garrisonHero && t->garrisonHero->hasArt(map->victoryCondition.objectId)))
  2003. {
  2004. return 1;
  2005. }
  2006. }
  2007. break;
  2008. }
  2009. }
  2010. return 0;
  2011. }
  2012. ui8 CGameState::checkForStandardWin() const
  2013. {
  2014. //std victory condition is:
  2015. //all enemies lost
  2016. TPlayerColor supposedWinner = 255, winnerTeam = 255;
  2017. for(auto i = players.begin(); i != players.end(); i++)
  2018. {
  2019. if(i->second.status == PlayerState::INGAME && i->first < GameConstants::PLAYER_LIMIT)
  2020. {
  2021. if(supposedWinner == 255)
  2022. {
  2023. //first player remaining ingame - candidate for victory
  2024. supposedWinner = i->second.color;
  2025. winnerTeam = i->second.team;
  2026. }
  2027. else if(winnerTeam != i->second.team)
  2028. {
  2029. //current candidate has enemy remaining in game -> no vicotry
  2030. return 255;
  2031. }
  2032. }
  2033. }
  2034. return supposedWinner;
  2035. }
  2036. bool CGameState::checkForStandardLoss( ui8 player ) const
  2037. {
  2038. //std loss condition is: player lost all towns and heroes
  2039. const PlayerState &p = *CGameInfoCallback::getPlayer(player);
  2040. return !p.heroes.size() && !p.towns.size();
  2041. }
  2042. struct statsHLP
  2043. {
  2044. typedef std::pair< TPlayerColor, si64 > TStat;
  2045. //converts [<player's color, value>] to vec[place] -> platers
  2046. static std::vector< std::vector< TPlayerColor > > getRank( std::vector<TStat> stats )
  2047. {
  2048. std::sort(stats.begin(), stats.end(), statsHLP());
  2049. //put first element
  2050. std::vector< std::vector<TPlayerColor> > ret;
  2051. std::vector<TPlayerColor> tmp;
  2052. tmp.push_back( stats[0].first );
  2053. ret.push_back( tmp );
  2054. //the rest of elements
  2055. for(int g=1; g<stats.size(); ++g)
  2056. {
  2057. if(stats[g].second == stats[g-1].second)
  2058. {
  2059. (ret.end()-1)->push_back( stats[g].first );
  2060. }
  2061. else
  2062. {
  2063. //create next occupied rank
  2064. std::vector<TPlayerColor> tmp;
  2065. tmp.push_back(stats[g].first);
  2066. ret.push_back(tmp);
  2067. }
  2068. }
  2069. return ret;
  2070. }
  2071. bool operator()(const TStat & a, const TStat & b) const
  2072. {
  2073. return a.second > b.second;
  2074. }
  2075. static const CGHeroInstance * findBestHero(CGameState * gs, int color)
  2076. {
  2077. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  2078. if(!h.size())
  2079. return NULL;
  2080. //best hero will be that with highest exp
  2081. int best = 0;
  2082. for(int b=1; b<h.size(); ++b)
  2083. {
  2084. if(h[b]->exp > h[best]->exp)
  2085. {
  2086. best = b;
  2087. }
  2088. }
  2089. return h[best];
  2090. }
  2091. //calculates total number of artifacts that belong to given player
  2092. static int getNumberOfArts(const PlayerState * ps)
  2093. {
  2094. int ret = 0;
  2095. BOOST_FOREACH(auto h, ps->heroes)
  2096. {
  2097. ret += h->artifactsInBackpack.size() + h->artifactsWorn.size();
  2098. }
  2099. return ret;
  2100. }
  2101. // get total strength of player army
  2102. static si64 getArmyStrength(const PlayerState * ps)
  2103. {
  2104. si64 str = 0;
  2105. BOOST_FOREACH(auto h, ps->heroes)
  2106. {
  2107. if(!h->inTownGarrison) //original h3 behavior
  2108. str += h->getArmyStrength();
  2109. }
  2110. return str;
  2111. }
  2112. };
  2113. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  2114. {
  2115. #define FILL_FIELD(FIELD, VAL_GETTER) \
  2116. { \
  2117. std::vector< std::pair< TPlayerColor, si64 > > stats; \
  2118. for(auto g = players.begin(); g != players.end(); ++g) \
  2119. { \
  2120. if(g->second.color == 255) \
  2121. continue; \
  2122. std::pair< ui8, si64 > stat; \
  2123. stat.first = g->second.color; \
  2124. stat.second = VAL_GETTER; \
  2125. stats.push_back(stat); \
  2126. } \
  2127. tgi.FIELD = statsHLP::getRank(stats); \
  2128. }
  2129. for(auto g = players.begin(); g != players.end(); ++g)
  2130. {
  2131. if(g->second.color != 255)
  2132. tgi.playerColors.push_back(g->second.color);
  2133. }
  2134. if(level >= 1) //num of towns & num of heroes
  2135. {
  2136. //num of towns
  2137. FILL_FIELD(numOfTowns, g->second.towns.size())
  2138. //num of heroes
  2139. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2140. //best hero's portrait
  2141. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2142. {
  2143. if(g->second.color == 255)
  2144. continue;
  2145. const CGHeroInstance * best = statsHLP::findBestHero(this, g->second.color);
  2146. InfoAboutHero iah;
  2147. iah.initFromHero(best, level >= 8);
  2148. iah.army.clear();
  2149. tgi.colorToBestHero[g->second.color] = iah;
  2150. }
  2151. }
  2152. if(level >= 2) //gold
  2153. {
  2154. FILL_FIELD(gold, g->second.resources[Res::GOLD])
  2155. }
  2156. if(level >= 2) //wood & ore
  2157. {
  2158. FILL_FIELD(woodOre, g->second.resources[Res::WOOD] + g->second.resources[Res::ORE])
  2159. }
  2160. if(level >= 3) //mercury, sulfur, crystal, gems
  2161. {
  2162. FILL_FIELD(mercSulfCrystGems, g->second.resources[Res::MERCURY] + g->second.resources[Res::SULFUR] + g->second.resources[Res::CRYSTAL] + g->second.resources[Res::GEMS])
  2163. }
  2164. if(level >= 4) //obelisks found
  2165. {
  2166. //TODO
  2167. }
  2168. if(level >= 5) //artifacts
  2169. {
  2170. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  2171. }
  2172. if(level >= 6) //army strength
  2173. {
  2174. FILL_FIELD(army, statsHLP::getArmyStrength(&g->second))
  2175. }
  2176. if(level >= 7) //income
  2177. {
  2178. //TODO
  2179. }
  2180. if(level >= 8) //best hero's stats
  2181. {
  2182. //already set in lvl 1 handling
  2183. }
  2184. if(level >= 9) //personality
  2185. {
  2186. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2187. {
  2188. if(g->second.color == 255) //do nothing for neutral player
  2189. continue;
  2190. if(g->second.human)
  2191. {
  2192. tgi.personality[g->second.color] = EAiTactic::NONE;
  2193. }
  2194. else //AI
  2195. {
  2196. tgi.personality[g->second.color] = map->players[g->second.color].aiTactic;
  2197. }
  2198. }
  2199. }
  2200. if(level >= 10) //best creature
  2201. {
  2202. //best creatures belonging to player (highest AI value)
  2203. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2204. {
  2205. if(g->second.color == 255) //do nothing for neutral player
  2206. continue;
  2207. int bestCre = -1; //best creature's ID
  2208. for(int b=0; b<g->second.heroes.size(); ++b)
  2209. {
  2210. for(TSlots::const_iterator it = g->second.heroes[b]->Slots().begin(); it != g->second.heroes[b]->Slots().end(); ++it)
  2211. {
  2212. int toCmp = it->second->type->idNumber; //ID of creature we should compare with the best one
  2213. if(bestCre == -1 || VLC->creh->creatures[bestCre]->AIValue < VLC->creh->creatures[toCmp]->AIValue)
  2214. {
  2215. bestCre = toCmp;
  2216. }
  2217. }
  2218. }
  2219. tgi.bestCreature[g->second.color] = bestCre;
  2220. }
  2221. }
  2222. #undef FILL_FIELD
  2223. }
  2224. int CGameState::lossCheck( ui8 player ) const
  2225. {
  2226. const PlayerState *p = CGameInfoCallback::getPlayer(player);
  2227. //if(map->lossCondition.typeOfLossCon == lossStandard)
  2228. if(checkForStandardLoss(player))
  2229. return -1;
  2230. if (p->enteredLosingCheatCode)
  2231. {
  2232. return 1;
  2233. }
  2234. if(p->human) //special loss condition applies only to human player
  2235. {
  2236. switch(map->lossCondition.typeOfLossCon)
  2237. {
  2238. case ELossConditionType::LOSSCASTLE:
  2239. {
  2240. const CGTownInstance *t = dynamic_cast<const CGTownInstance *>(map->lossCondition.obj);
  2241. assert(t);
  2242. if(t->tempOwner != player)
  2243. return 1;
  2244. }
  2245. break;
  2246. case ELossConditionType::LOSSHERO:
  2247. {
  2248. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(map->lossCondition.obj);
  2249. assert(h);
  2250. if(h->tempOwner != player)
  2251. return 1;
  2252. }
  2253. break;
  2254. case ELossConditionType::TIMEEXPIRES:
  2255. if(map->lossCondition.timeLimit < day)
  2256. return 1;
  2257. break;
  2258. }
  2259. }
  2260. if(!p->towns.size() && p->daysWithoutCastle >= 7)
  2261. return 2;
  2262. return false;
  2263. }
  2264. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > CGameState::unusedHeroesFromPool()
  2265. {
  2266. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > pool = hpool.heroesPool;
  2267. for ( auto i = players.cbegin() ; i != players.cend();i++)
  2268. for(auto j = i->second.availableHeroes.cbegin(); j != i->second.availableHeroes.cend(); j++)
  2269. if(*j)
  2270. pool.erase((**j).subID);
  2271. return pool;
  2272. }
  2273. void CGameState::buildBonusSystemTree()
  2274. {
  2275. buildGlobalTeamPlayerTree();
  2276. attachArmedObjects();
  2277. BOOST_FOREACH(CGTownInstance *t, map->towns)
  2278. {
  2279. t->deserializationFix();
  2280. }
  2281. // CStackInstance <-> CCreature, CStackInstance <-> CArmedInstance, CArtifactInstance <-> CArtifact
  2282. // are provided on initializing / deserializing
  2283. }
  2284. void CGameState::deserializationFix()
  2285. {
  2286. buildGlobalTeamPlayerTree();
  2287. attachArmedObjects();
  2288. }
  2289. void CGameState::buildGlobalTeamPlayerTree()
  2290. {
  2291. for(auto k=teams.begin(); k!=teams.end(); ++k)
  2292. {
  2293. TeamState *t = &k->second;
  2294. t->attachTo(&globalEffects);
  2295. BOOST_FOREACH(ui8 teamMember, k->second.players)
  2296. {
  2297. PlayerState *p = getPlayer(teamMember);
  2298. assert(p);
  2299. p->attachTo(t);
  2300. }
  2301. }
  2302. }
  2303. void CGameState::attachArmedObjects()
  2304. {
  2305. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  2306. {
  2307. if(CArmedInstance *armed = dynamic_cast<CArmedInstance*>(obj))
  2308. armed->whatShouldBeAttached()->attachTo(armed->whereShouldBeAttached(this));
  2309. }
  2310. }
  2311. void CGameState::giveHeroArtifact(CGHeroInstance *h, int aid)
  2312. {
  2313. CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  2314. CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  2315. map->addNewArtifactInstance(ai);
  2316. ai->putAt(ArtifactLocation(h, ai->firstAvailableSlot(h)));
  2317. }
  2318. int3 CPath::startPos() const
  2319. {
  2320. return nodes[nodes.size()-1].coord;
  2321. }
  2322. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  2323. {
  2324. if (mode==0)
  2325. {
  2326. for (ui32 i=0;i<nodes.size();i++)
  2327. {
  2328. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2329. }
  2330. }
  2331. }
  2332. int3 CPath::endPos() const
  2333. {
  2334. return nodes[0].coord;
  2335. }
  2336. CGPathNode::CGPathNode()
  2337. :coord(-1,-1,-1)
  2338. {
  2339. accessible = 0;
  2340. land = 0;
  2341. moveRemains = 0;
  2342. turns = 255;
  2343. theNodeBefore = NULL;
  2344. }
  2345. bool CGPathNode::reachable() const
  2346. {
  2347. return turns < 255;
  2348. }
  2349. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  2350. {
  2351. assert(isValid);
  2352. out.nodes.clear();
  2353. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  2354. if(!curnode->theNodeBefore)
  2355. return false;
  2356. while(curnode)
  2357. {
  2358. CGPathNode cpn = *curnode;
  2359. curnode = curnode->theNodeBefore;
  2360. out.nodes.push_back(cpn);
  2361. }
  2362. return true;
  2363. }
  2364. CPathsInfo::CPathsInfo( const int3 &Sizes )
  2365. :sizes(Sizes)
  2366. {
  2367. hero = NULL;
  2368. nodes = new CGPathNode**[sizes.x];
  2369. for(int i = 0; i < sizes.x; i++)
  2370. {
  2371. nodes[i] = new CGPathNode*[sizes.y];
  2372. for (int j = 0; j < sizes.y; j++)
  2373. {
  2374. nodes[i][j] = new CGPathNode[sizes.z];
  2375. }
  2376. }
  2377. }
  2378. CPathsInfo::~CPathsInfo()
  2379. {
  2380. for(int i = 0; i < sizes.x; i++)
  2381. {
  2382. for (int j = 0; j < sizes.y; j++)
  2383. {
  2384. delete [] nodes[i][j];
  2385. }
  2386. delete [] nodes[i];
  2387. }
  2388. delete [] nodes;
  2389. }
  2390. int3 CGPath::startPos() const
  2391. {
  2392. return nodes[nodes.size()-1].coord;
  2393. }
  2394. int3 CGPath::endPos() const
  2395. {
  2396. return nodes[0].coord;
  2397. }
  2398. void CGPath::convert( ui8 mode )
  2399. {
  2400. if(mode==0)
  2401. {
  2402. for(ui32 i=0;i<nodes.size();i++)
  2403. {
  2404. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2405. }
  2406. }
  2407. }
  2408. PlayerState::PlayerState()
  2409. : color(-1), currentSelection(0xffffffff), enteredWinningCheatCode(0),
  2410. enteredLosingCheatCode(0), status(INGAME), daysWithoutCastle(0)
  2411. {
  2412. setNodeType(PLAYER);
  2413. }
  2414. std::string PlayerState::nodeName() const
  2415. {
  2416. return "Player " + (color < VLC->generaltexth->capColors.size() ? VLC->generaltexth->capColors[color] : boost::lexical_cast<std::string>(color));
  2417. }
  2418. // void PlayerState::getParents(TCNodes &out, const CBonusSystemNode *root /*= NULL*/) const
  2419. // {
  2420. // return; //no loops possible
  2421. // }
  2422. //
  2423. // void PlayerState::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  2424. // {
  2425. // for (std::vector<CGHeroInstance *>::const_iterator it = heroes.begin(); it != heroes.end(); it++)
  2426. // {
  2427. // if (*it != root)
  2428. // (*it)->getBonuses(out, selector, this);
  2429. // }
  2430. // }
  2431. InfoAboutArmy::InfoAboutArmy():
  2432. owner(GameConstants::NEUTRAL_PLAYER)
  2433. {}
  2434. InfoAboutArmy::InfoAboutArmy(const CArmedInstance *Army, bool detailed)
  2435. {
  2436. initFromArmy(Army, detailed);
  2437. }
  2438. void InfoAboutArmy::initFromArmy(const CArmedInstance *Army, bool detailed)
  2439. {
  2440. army = ArmyDescriptor(Army, detailed);
  2441. owner = Army->tempOwner;
  2442. name = Army->getHoverText();
  2443. }
  2444. void InfoAboutHero::assign(const InfoAboutHero & iah)
  2445. {
  2446. InfoAboutArmy::operator = (iah);
  2447. details = (iah.details ? new Details(*iah.details) : NULL);
  2448. hclass = iah.hclass;
  2449. portrait = iah.portrait;
  2450. }
  2451. InfoAboutHero::InfoAboutHero():
  2452. details(nullptr),
  2453. hclass(nullptr),
  2454. portrait(-1)
  2455. {}
  2456. InfoAboutHero::InfoAboutHero(const InfoAboutHero & iah):
  2457. InfoAboutArmy()
  2458. {
  2459. assign(iah);
  2460. }
  2461. InfoAboutHero::InfoAboutHero(const CGHeroInstance *h, bool detailed)
  2462. {
  2463. initFromHero(h, detailed);
  2464. }
  2465. InfoAboutHero::~InfoAboutHero()
  2466. {
  2467. delete details;
  2468. }
  2469. InfoAboutHero & InfoAboutHero::operator=(const InfoAboutHero & iah)
  2470. {
  2471. assign(iah);
  2472. return *this;
  2473. }
  2474. void InfoAboutHero::initFromHero(const CGHeroInstance *h, bool detailed)
  2475. {
  2476. if(!h)
  2477. return;
  2478. initFromArmy(h, detailed);
  2479. hclass = h->type->heroClass;
  2480. name = h->name;
  2481. portrait = h->portrait;
  2482. if(detailed)
  2483. {
  2484. //include details about hero
  2485. details = new Details;
  2486. details->luck = h->LuckVal();
  2487. details->morale = h->MoraleVal();
  2488. details->mana = h->mana;
  2489. details->primskills.resize(GameConstants::PRIMARY_SKILLS);
  2490. for (int i = 0; i < GameConstants::PRIMARY_SKILLS ; i++)
  2491. {
  2492. details->primskills[i] = h->getPrimSkillLevel(i);
  2493. }
  2494. }
  2495. }
  2496. InfoAboutTown::InfoAboutTown():
  2497. details(nullptr),
  2498. tType(nullptr),
  2499. built(0),
  2500. fortLevel(0)
  2501. {
  2502. }
  2503. InfoAboutTown::InfoAboutTown(const CGTownInstance *t, bool detailed)
  2504. {
  2505. initFromTown(t, detailed);
  2506. }
  2507. InfoAboutTown::~InfoAboutTown()
  2508. {
  2509. delete details;
  2510. }
  2511. void InfoAboutTown::initFromTown(const CGTownInstance *t, bool detailed)
  2512. {
  2513. initFromArmy(t, detailed);
  2514. army = ArmyDescriptor(t->getUpperArmy(), detailed);
  2515. built = t->builded;
  2516. fortLevel = t->fortLevel();
  2517. name = t->name;
  2518. tType = t->town;
  2519. if(detailed)
  2520. {
  2521. //include details about hero
  2522. details = new Details;
  2523. details->goldIncome = t->dailyIncome();
  2524. details->customRes = t->hasBuilt(EBuilding::RESOURCE_SILO);
  2525. details->hallLevel = t->hallLevel();
  2526. details->garrisonedHero = t->garrisonHero;
  2527. }
  2528. }
  2529. ArmyDescriptor::ArmyDescriptor(const CArmedInstance *army, bool detailed)
  2530. : isDetailed(detailed)
  2531. {
  2532. for(TSlots::const_iterator i = army->Slots().begin(); i != army->Slots().end(); i++)
  2533. {
  2534. if(detailed)
  2535. (*this)[i->first] = *i->second;
  2536. else
  2537. (*this)[i->first] = CStackBasicDescriptor(i->second->type, i->second->getQuantityID());
  2538. }
  2539. }
  2540. ArmyDescriptor::ArmyDescriptor()
  2541. : isDetailed(false)
  2542. {
  2543. }
  2544. int ArmyDescriptor::getStrength() const
  2545. {
  2546. ui64 ret = 0;
  2547. if(isDetailed)
  2548. {
  2549. for(const_iterator i = begin(); i != end(); i++)
  2550. ret += i->second.type->AIValue * i->second.count;
  2551. }
  2552. else
  2553. {
  2554. for(const_iterator i = begin(); i != end(); i++)
  2555. ret += i->second.type->AIValue * CCreature::estimateCreatureCount(i->second.count);
  2556. }
  2557. return ret;
  2558. }
  2559. DuelParameters::SideSettings::StackSettings::StackSettings()
  2560. : type(-1), count(0)
  2561. {
  2562. }
  2563. DuelParameters::SideSettings::StackSettings::StackSettings(si32 Type, si32 Count)
  2564. : type(Type), count(Count)
  2565. {
  2566. }
  2567. DuelParameters::SideSettings::SideSettings()
  2568. {
  2569. heroId = -1;
  2570. }
  2571. DuelParameters::DuelParameters()
  2572. {
  2573. terType = ETerrainType::DIRT;
  2574. bfieldType = 15;
  2575. }
  2576. DuelParameters DuelParameters::fromJSON(const std::string &fname)
  2577. {
  2578. DuelParameters ret;
  2579. const JsonNode duelData(ResourceID("DATA/" + fname, EResType::TEXT));
  2580. ret.terType = duelData["terType"].Float();
  2581. ret.bfieldType = duelData["bfieldType"].Float();
  2582. BOOST_FOREACH(const JsonNode &n, duelData["sides"].Vector())
  2583. {
  2584. SideSettings &ss = ret.sides[(int)n["side"].Float()];
  2585. int i = 0;
  2586. BOOST_FOREACH(const JsonNode &stackNode, n["army"].Vector())
  2587. {
  2588. ss.stacks[i].type = stackNode.Vector()[0].Float();
  2589. ss.stacks[i].count = stackNode.Vector()[1].Float();
  2590. i++;
  2591. }
  2592. if(n["heroid"].getType() == JsonNode::DATA_FLOAT)
  2593. ss.heroId = n["heroid"].Float();
  2594. else
  2595. ss.heroId = -1;
  2596. BOOST_FOREACH(const JsonNode &n, n["heroPrimSkills"].Vector())
  2597. ss.heroPrimSkills.push_back(n.Float());
  2598. BOOST_FOREACH(const JsonNode &skillNode, n["heroSecSkills"].Vector())
  2599. {
  2600. std::pair<si32, si8> secSkill;
  2601. secSkill.first = skillNode.Vector()[0].Float();
  2602. secSkill.second = skillNode.Vector()[1].Float();
  2603. ss.heroSecSkills.push_back(secSkill);
  2604. }
  2605. assert(ss.heroPrimSkills.empty() || ss.heroPrimSkills.size() == GameConstants::PRIMARY_SKILLS);
  2606. if(ss.heroId != -1)
  2607. {
  2608. const JsonNode & spells = n["spells"];
  2609. if(spells.getType() == JsonNode::DATA_STRING && spells.String() == "all")
  2610. {
  2611. BOOST_FOREACH(auto spell, VLC->spellh->spells)
  2612. if(spell->id <= Spells::SUMMON_AIR_ELEMENTAL)
  2613. ss.spells.insert(spell->id);
  2614. }
  2615. else
  2616. BOOST_FOREACH(const JsonNode &spell, n["spells"].Vector())
  2617. ss.spells.insert(spell.Float());
  2618. }
  2619. }
  2620. BOOST_FOREACH(const JsonNode &n, duelData["obstacles"].Vector())
  2621. {
  2622. auto oi = make_shared<CObstacleInstance>();
  2623. if(n.getType() == JsonNode::DATA_VECTOR)
  2624. {
  2625. oi->ID = n.Vector()[0].Float();
  2626. oi->pos = n.Vector()[1].Float();
  2627. }
  2628. else
  2629. {
  2630. assert(n.getType() == JsonNode::DATA_FLOAT);
  2631. oi->ID = 21;
  2632. oi->pos = n.Float();
  2633. }
  2634. oi->uniqueID = ret.obstacles.size();
  2635. ret.obstacles.push_back(oi);
  2636. }
  2637. BOOST_FOREACH(const JsonNode &n, duelData["creatures"].Vector())
  2638. {
  2639. CusomCreature cc;
  2640. cc.id = n["id"].Float();
  2641. #define retreive(name) \
  2642. if(n[ #name ].getType() == JsonNode::DATA_FLOAT)\
  2643. cc.name = n[ #name ].Float(); \
  2644. else \
  2645. cc.name = -1;
  2646. retreive(attack);
  2647. retreive(defense);
  2648. retreive(HP);
  2649. retreive(dmg);
  2650. retreive(shoots);
  2651. retreive(speed);
  2652. ret.creatures.push_back(cc);
  2653. }
  2654. return ret;
  2655. }
  2656. TeamState::TeamState()
  2657. {
  2658. setNodeType(TEAM);
  2659. }
  2660. void CPathfinder::initializeGraph()
  2661. {
  2662. CGPathNode ***graph = out.nodes;
  2663. for(size_t i=0; i < out.sizes.x; ++i)
  2664. {
  2665. for(size_t j=0; j < out.sizes.y; ++j)
  2666. {
  2667. for(size_t k=0; k < out.sizes.z; ++k)
  2668. {
  2669. curPos = int3(i,j,k);
  2670. const TerrainTile *tinfo = &gs->map->terrain[i][j][k];
  2671. CGPathNode &node = graph[i][j][k];
  2672. node.accessible = evaluateAccessibility(tinfo);
  2673. node.turns = 0xff;
  2674. node.moveRemains = 0;
  2675. node.coord.x = i;
  2676. node.coord.y = j;
  2677. node.coord.z = k;
  2678. node.land = tinfo->terType != ETerrainType::WATER;
  2679. node.theNodeBefore = NULL;
  2680. }
  2681. }
  2682. }
  2683. }
  2684. void CPathfinder::calculatePaths(int3 src /*= int3(-1,-1,-1)*/, int movement /*= -1*/)
  2685. {
  2686. assert(hero);
  2687. assert(hero == getHero(hero->id));
  2688. if(src.x < 0)
  2689. src = hero->getPosition(false);
  2690. if(movement < 0)
  2691. movement = hero->movement;
  2692. out.hero = hero;
  2693. out.hpos = src;
  2694. if(!gs->map->isInTheMap(src)/* || !gs->map->isInTheMap(dest)*/) //check input
  2695. {
  2696. tlog1 << "CGameState::calculatePaths: Hero outside the gs->map? How dare you...\n";
  2697. return;
  2698. }
  2699. initializeGraph();
  2700. //initial tile - set cost on 0 and add to the queue
  2701. CGPathNode &initialNode = *getNode(src);
  2702. initialNode.turns = 0;
  2703. initialNode.moveRemains = movement;
  2704. mq.push_back(&initialNode);
  2705. std::vector<int3> neighbours;
  2706. neighbours.reserve(16);
  2707. while(!mq.empty())
  2708. {
  2709. cp = mq.front();
  2710. mq.pop_front();
  2711. const int3 sourceGuardPosition = guardingCreaturePosition(cp->coord);
  2712. bool guardedSource = (sourceGuardPosition != int3(-1, -1, -1) && cp->coord != src);
  2713. ct = &gs->map->getTile(cp->coord);
  2714. int movement = cp->moveRemains, turn = cp->turns;
  2715. if(!movement)
  2716. {
  2717. movement = hero->maxMovePoints(cp->land);
  2718. turn++;
  2719. }
  2720. //add accessible neighbouring nodes to the queue
  2721. neighbours.clear();
  2722. //handling subterranean gate => it's exit is the only neighbour
  2723. bool subterraneanEntry = (ct->topVisitableId() == Obj::SUBTERRANEAN_GATE && useSubterraneanGates);
  2724. if(subterraneanEntry)
  2725. {
  2726. //try finding the exit gate
  2727. if(const CGObjectInstance *outGate = getObj(CGTeleport::getMatchingGate(ct->visitableObjects.back()->id), false))
  2728. {
  2729. const int3 outPos = outGate->visitablePos();
  2730. //gs->getNeighbours(*getTile(outPos), outPos, neighbours, boost::logic::indeterminate, !cp->land);
  2731. neighbours.push_back(outPos);
  2732. }
  2733. else
  2734. {
  2735. //gate with no exit (blocked) -> do nothing with this node
  2736. continue;
  2737. }
  2738. }
  2739. gs->getNeighbours(*ct, cp->coord, neighbours, boost::logic::indeterminate, !cp->land);
  2740. for(ui32 i=0; i < neighbours.size(); i++)
  2741. {
  2742. const int3 &n = neighbours[i]; //current neighbor
  2743. dp = getNode(n);
  2744. dt = &gs->map->getTile(n);
  2745. destTopVisObjID = dt->topVisitableId();
  2746. useEmbarkCost = 0; //0 - usual movement; 1 - embark; 2 - disembark
  2747. int turnAtNextTile = turn;
  2748. const bool destIsGuardian = sourceGuardPosition == n;
  2749. if(!goodForLandSeaTransition())
  2750. continue;
  2751. if(!canMoveBetween(cp->coord, dp->coord) || dp->accessible == CGPathNode::BLOCKED )
  2752. continue;
  2753. //special case -> hero embarked a boat standing on a guarded tile -> we must allow to move away from that tile
  2754. if(cp->accessible == CGPathNode::VISITABLE && guardedSource && cp->theNodeBefore->land && ct->topVisitableId() == Obj::BOAT)
  2755. guardedSource = false;
  2756. int cost = gs->getMovementCost(hero, cp->coord, dp->coord, movement);
  2757. //special case -> moving from src Subterranean gate to dest gate -> it's free
  2758. if(subterraneanEntry && destTopVisObjID == Obj::SUBTERRANEAN_GATE && cp->coord.z != dp->coord.z)
  2759. cost = 0;
  2760. int remains = movement - cost;
  2761. if(useEmbarkCost)
  2762. {
  2763. remains = hero->movementPointsAfterEmbark(movement, cost, useEmbarkCost - 1);
  2764. cost = movement - remains;
  2765. }
  2766. if(remains < 0)
  2767. {
  2768. //occurs rarely, when hero with low movepoints tries to leave the road
  2769. turnAtNextTile++;
  2770. int moveAtNextTile = hero->maxMovePoints(cp->land);
  2771. cost = gs->getMovementCost(hero, cp->coord, dp->coord, moveAtNextTile); //cost must be updated, movement points changed :(
  2772. remains = moveAtNextTile - cost;
  2773. }
  2774. if((dp->turns==0xff //we haven't been here before
  2775. || dp->turns > turnAtNextTile
  2776. || (dp->turns >= turnAtNextTile && dp->moveRemains < remains)) //this route is faster
  2777. && (!guardedSource || destIsGuardian)) // Can step into tile of guard
  2778. {
  2779. assert(dp != cp->theNodeBefore); //two tiles can't point to each other
  2780. dp->moveRemains = remains;
  2781. dp->turns = turnAtNextTile;
  2782. dp->theNodeBefore = cp;
  2783. const bool guardedDst = guardingCreaturePosition(dp->coord) != int3(-1, -1, -1)
  2784. && dp->accessible == CGPathNode::BLOCKVIS;
  2785. if (dp->accessible == CGPathNode::ACCESSIBLE
  2786. || (useEmbarkCost && allowEmbarkAndDisembark)
  2787. || destTopVisObjID == Obj::SUBTERRANEAN_GATE
  2788. || (guardedDst && !guardedSource)) // Can step into a hostile tile once.
  2789. {
  2790. mq.push_back(dp);
  2791. }
  2792. }
  2793. } //neighbours loop
  2794. } //queue loop
  2795. out.isValid = true;
  2796. }
  2797. CGPathNode *CPathfinder::getNode(const int3 &coord)
  2798. {
  2799. return &out.nodes[coord.x][coord.y][coord.z];
  2800. }
  2801. bool CPathfinder::canMoveBetween(const int3 &a, const int3 &b) const
  2802. {
  2803. return gs->checkForVisitableDir(a, b) && gs->checkForVisitableDir(b, a);
  2804. }
  2805. bool CPathfinder::canStepOntoDst() const
  2806. {
  2807. //TODO remove
  2808. assert(0);
  2809. return false;
  2810. }
  2811. CGPathNode::EAccessibility CPathfinder::evaluateAccessibility(const TerrainTile *tinfo) const
  2812. {
  2813. CGPathNode::EAccessibility ret = (tinfo->blocked ? CGPathNode::BLOCKED : CGPathNode::ACCESSIBLE);
  2814. if(tinfo->terType == ETerrainType::ROCK || !FoW[curPos.x][curPos.y][curPos.z])
  2815. return CGPathNode::BLOCKED;
  2816. if(tinfo->visitable)
  2817. {
  2818. if(tinfo->visitableObjects.front()->ID == 80 && tinfo->visitableObjects.back()->ID == Obj::HERO && tinfo->visitableObjects.back()->tempOwner != hero->tempOwner) //non-owned hero stands on Sanctuary
  2819. {
  2820. return CGPathNode::BLOCKED;
  2821. }
  2822. else
  2823. {
  2824. BOOST_FOREACH(const CGObjectInstance *obj, tinfo->visitableObjects)
  2825. {
  2826. if(obj->getPassableness() & 1<<hero->tempOwner) //special object instance specific passableness flag - overwrites other accessibility flags
  2827. {
  2828. ret = CGPathNode::ACCESSIBLE;
  2829. }
  2830. else if(obj->blockVisit)
  2831. {
  2832. return CGPathNode::BLOCKVIS;
  2833. }
  2834. else if(obj->ID != Obj::EVENT) //pathfinder should ignore placed events
  2835. {
  2836. ret = CGPathNode::VISITABLE;
  2837. }
  2838. }
  2839. }
  2840. }
  2841. else if (gs->map->isInTheMap(guardingCreaturePosition(curPos))
  2842. && !tinfo->blocked)
  2843. {
  2844. // Monster close by; blocked visit for battle.
  2845. return CGPathNode::BLOCKVIS;
  2846. }
  2847. return ret;
  2848. }
  2849. bool CPathfinder::goodForLandSeaTransition()
  2850. {
  2851. if(cp->land != dp->land) //hero can traverse land<->sea only in special circumstances
  2852. {
  2853. if(cp->land) //from land to sea -> embark or assault hero on boat
  2854. {
  2855. if(dp->accessible == CGPathNode::ACCESSIBLE || destTopVisObjID < 0) //cannot enter empty water tile from land -> it has to be visitable
  2856. return false;
  2857. if(destTopVisObjID != Obj::HERO && destTopVisObjID != Obj::BOAT) //only boat or hero can be accessed from land
  2858. return false;
  2859. if(destTopVisObjID == Obj::BOAT)
  2860. useEmbarkCost = 1;
  2861. }
  2862. else //disembark
  2863. {
  2864. //can disembark only on coastal tiles
  2865. if(!dt->isCoastal())
  2866. return false;
  2867. //tile must be accessible -> exception: unblocked blockvis tiles -> clear but guarded by nearby monster coast
  2868. if( (dp->accessible != CGPathNode::ACCESSIBLE && (dp->accessible != CGPathNode::BLOCKVIS || dt->blocked))
  2869. || dt->visitable) //TODO: passableness problem -> town says it's passable (thus accessible) but we obviously can't disembark onto town gate
  2870. return false;;
  2871. useEmbarkCost = 2;
  2872. }
  2873. }
  2874. return true;
  2875. }
  2876. CPathfinder::CPathfinder(CPathsInfo &_out, CGameState *_gs, const CGHeroInstance *_hero) : CGameInfoCallback(_gs, -1), out(_out), hero(_hero), FoW(getPlayerTeam(hero->tempOwner)->fogOfWarMap)
  2877. {
  2878. useSubterraneanGates = true;
  2879. allowEmbarkAndDisembark = true;
  2880. }