CGameState.cpp 85 KB

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