CGameState.cpp 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148
  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. auto bonus = scenarioOps->campState->getBonusForCurrentMap();
  900. if(bonus.is_initialized())
  901. {
  902. for(auto it = scenarioOps->playerInfos.begin(); it != scenarioOps->playerInfos.end(); ++it)
  903. {
  904. const PlayerInfo &p = map->players[it->first];
  905. bool campaignGiveHero = it->second.human && scenarioOps->mode == StartInfo::CAMPAIGN &&
  906. bonus.get().type == CScenarioTravel::STravelBonus::HERO;
  907. bool generateHero = (p.generateHeroAtMainTown || campaignGiveHero) && p.hasMainTown;
  908. if(generateHero && vstd::contains(scenarioOps->playerInfos, it->first))
  909. {
  910. int3 hpos = p.posOfMainTown;
  911. hpos.x+=1;
  912. int h = pickHero(it->first);
  913. if(it->second.hero == -1)
  914. it->second.hero = h;
  915. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(Obj::HERO,h,hpos,it->first));
  916. nnn->id = map->objects.size();
  917. nnn->initHero();
  918. map->heroes.push_back(nnn);
  919. map->objects.push_back(nnn);
  920. map->addBlockVisTiles(nnn);
  921. }
  922. }
  923. }
  924. }
  925. /*************************replace hero placeholders*****************************/
  926. tlog4 << "\tReplacing hero placeholders";
  927. if (scenarioOps->campState)
  928. {
  929. auto campaign = scenarioOps->campState;
  930. auto bonus = campaign->getBonusForCurrentMap();
  931. if(bonus.is_initialized())
  932. {
  933. std::vector<CGHeroInstance *> Xheroes;
  934. if (bonus->type == CScenarioTravel::STravelBonus::PLAYER_PREV_SCENARIO)
  935. {
  936. Xheroes = campaign->camp->scenarios[bonus->info2].crossoverHeroes;
  937. }
  938. //selecting heroes by type
  939. for(int g=0; g<map->objects.size(); ++g)
  940. {
  941. CGObjectInstance * obj = map->objects[g];
  942. if (obj->ID != Obj::HERO_PLACEHOLDER)
  943. {
  944. continue;
  945. }
  946. CGHeroPlaceholder * hp = static_cast<CGHeroPlaceholder*>(obj);
  947. if(hp->subID != 0xFF) //select by type
  948. {
  949. bool found = false;
  950. BOOST_FOREACH(CGHeroInstance * ghi, Xheroes)
  951. {
  952. if (ghi->subID == hp->subID)
  953. {
  954. found = true;
  955. replaceHero(g, ghi);
  956. Xheroes -= ghi;
  957. break;
  958. }
  959. }
  960. if (!found)
  961. {
  962. //TODO: create new hero of this type
  963. }
  964. }
  965. }
  966. //selecting heroes by power
  967. std::sort(Xheroes.begin(), Xheroes.end(), [](const CGHeroInstance * a, const CGHeroInstance * b)
  968. {
  969. return a->getHeroStrength() > b->getHeroStrength();
  970. }); //sort, descending strength
  971. for(int g=0; g<map->objects.size(); ++g)
  972. {
  973. CGObjectInstance * obj = map->objects[g];
  974. if (obj->ID != Obj::HERO_PLACEHOLDER)
  975. {
  976. continue;
  977. }
  978. CGHeroPlaceholder * hp = static_cast<CGHeroPlaceholder*>(obj);
  979. if (hp->subID == 0xFF) //select by power
  980. {
  981. if(Xheroes.size() > hp->power - 1)
  982. replaceHero(g, Xheroes[hp->power - 1]);
  983. else
  984. tlog2 << "Warning, to hero to replace!\n";
  985. //we don't have to remove hero from Xheroes because it would destroy the order and duplicates shouldn't happen
  986. }
  987. }
  988. }
  989. }
  990. /******************RESOURCES****************************************************/
  991. tlog4 << "\tSetting up resources";
  992. const JsonNode config(ResourceID("config/startres.json"));
  993. const JsonVector &vector = config["difficulty"].Vector();
  994. const JsonNode &level = vector[scenarioOps->difficulty];
  995. TResources startresAI(level["ai"]);
  996. TResources startresHuman(level["human"]);
  997. for (auto i = players.begin(); i!=players.end(); i++)
  998. {
  999. PlayerState &p = i->second;
  1000. if (p.human)
  1001. p.resources = startresHuman;
  1002. else
  1003. p.resources = startresAI;
  1004. }
  1005. //give start resource bonus in case of campaign
  1006. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1007. {
  1008. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1009. if(chosenBonus.is_initialized() && chosenBonus->type == CScenarioTravel::STravelBonus::RESOURCE)
  1010. {
  1011. std::vector<const PlayerSettings *> people = getHumanPlayerInfo(); //players we will give resource bonus
  1012. BOOST_FOREACH(const PlayerSettings *ps, people)
  1013. {
  1014. std::vector<int> res; //resources we will give
  1015. switch (chosenBonus->info1)
  1016. {
  1017. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  1018. res.push_back(chosenBonus->info1);
  1019. break;
  1020. case 0xFD: //wood+ore
  1021. res.push_back(Res::WOOD); res.push_back(Res::ORE);
  1022. break;
  1023. case 0xFE: //rare
  1024. res.push_back(Res::MERCURY); res.push_back(Res::SULFUR); res.push_back(Res::CRYSTAL); res.push_back(Res::GEMS);
  1025. break;
  1026. default:
  1027. assert(0);
  1028. break;
  1029. }
  1030. //increasing resource quantity
  1031. for (int n=0; n<res.size(); ++n)
  1032. {
  1033. players[ps->color].resources[res[n]] += chosenBonus->info2;
  1034. }
  1035. }
  1036. }
  1037. }
  1038. /*************************HEROES************************************************/
  1039. tlog4 << "\tSetting up heroes";
  1040. std::set<int> hids; //hero ids to create pool
  1041. for(ui32 i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1042. if(map->allowedHeroes[i])
  1043. hids.insert(i);
  1044. for (ui32 i=0; i<map->heroes.size();i++) //heroes instances initialization
  1045. {
  1046. if (map->heroes[i]->getOwner()<0)
  1047. {
  1048. tlog2 << "Warning - hero with uninitialized owner!\n";
  1049. continue;
  1050. }
  1051. CGHeroInstance * vhi = (map->heroes[i]);
  1052. vhi->initHero();
  1053. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1054. hids.erase(vhi->subID);
  1055. }
  1056. for (ui32 i=0; i<map->objects.size();i++) //prisons
  1057. {
  1058. if (map->objects[i]->ID == Obj::PRISON)
  1059. hids.erase(map->objects[i]->subID);
  1060. }
  1061. for(ui32 i=0; i<map->predefinedHeroes.size(); i++)
  1062. {
  1063. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1064. continue;
  1065. map->predefinedHeroes[i]->initHero();
  1066. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1067. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1068. hids.erase(map->predefinedHeroes[i]->subID);
  1069. }
  1070. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go with default state into the pool
  1071. {
  1072. CGHeroInstance * vhi = new CGHeroInstance();
  1073. vhi->initHero(hid);
  1074. hpool.heroesPool[hid] = vhi;
  1075. hpool.pavailable[hid] = 0xff;
  1076. }
  1077. for(ui32 i=0; i<map->disposedHeroes.size(); i++)
  1078. {
  1079. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1080. }
  1081. if (scenarioOps->mode == StartInfo::CAMPAIGN) //give campaign bonuses for specific / best hero
  1082. {
  1083. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1084. if (chosenBonus.is_initialized() && chosenBonus->isBonusForHero() && chosenBonus->info1 != 0xFFFE) //exclude generated heroes
  1085. {
  1086. //find human player
  1087. int humanPlayer=GameConstants::NEUTRAL_PLAYER;
  1088. for (auto it=players.begin(); it != players.end(); ++it)
  1089. {
  1090. if(it->second.human)
  1091. {
  1092. humanPlayer = it->first;
  1093. break;
  1094. }
  1095. }
  1096. assert(humanPlayer != GameConstants::NEUTRAL_PLAYER);
  1097. std::vector<ConstTransitivePtr<CGHeroInstance> > & heroes = players[humanPlayer].heroes;
  1098. if (chosenBonus->info1 == 0xFFFD) //most powerful
  1099. {
  1100. int maxB = -1;
  1101. for (int b=0; b<heroes.size(); ++b)
  1102. {
  1103. if (maxB == -1 || heroes[b]->getTotalStrength() > heroes[maxB]->getTotalStrength())
  1104. {
  1105. maxB = b;
  1106. }
  1107. }
  1108. if(maxB < 0)
  1109. tlog2 << "Warning - cannot give bonus to hero cause there are no heroes!\n";
  1110. else
  1111. giveCampaignBonusToHero(heroes[maxB]);
  1112. }
  1113. else //specific hero
  1114. {
  1115. for (int b=0; b<heroes.size(); ++b)
  1116. {
  1117. if (heroes[b]->subID == chosenBonus->info1)
  1118. {
  1119. giveCampaignBonusToHero(heroes[b]);
  1120. break;
  1121. }
  1122. }
  1123. }
  1124. }
  1125. }
  1126. /*************************FOG**OF**WAR******************************************/
  1127. tlog4 << "\tFog of war";
  1128. for(auto k=teams.begin(); k!=teams.end(); ++k)
  1129. {
  1130. k->second.fogOfWarMap.resize(map->width);
  1131. for(int g=0; g<map->width; ++g)
  1132. k->second.fogOfWarMap[g].resize(map->height);
  1133. for(int g=-0; g<map->width; ++g)
  1134. for(int h=0; h<map->height; ++h)
  1135. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1136. for(int g=0; g<map->width; ++g)
  1137. for(int h=0; h<map->height; ++h)
  1138. for(int v=0; v<map->twoLevel+1; ++v)
  1139. k->second.fogOfWarMap[g][h][v] = 0;
  1140. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1141. {
  1142. if( !vstd::contains(k->second.players, obj->tempOwner)) continue; //not a flagged object
  1143. boost::unordered_set<int3, ShashInt3> tiles;
  1144. obj->getSightTiles(tiles);
  1145. BOOST_FOREACH(int3 tile, tiles)
  1146. {
  1147. k->second.fogOfWarMap[tile.x][tile.y][tile.z] = 1;
  1148. }
  1149. }
  1150. }
  1151. tlog4 << "\tStarting bonuses";
  1152. for(auto k=players.begin(); k!=players.end(); ++k)
  1153. {
  1154. //starting bonus
  1155. if(scenarioOps->playerInfos[k->first].bonus==PlayerSettings::brandom)
  1156. scenarioOps->playerInfos[k->first].bonus = ran()%3;
  1157. switch(scenarioOps->playerInfos[k->first].bonus)
  1158. {
  1159. case PlayerSettings::bgold:
  1160. k->second.resources[Res::GOLD] += 500 + (ran()%6)*100;
  1161. break;
  1162. case PlayerSettings::bresource:
  1163. {
  1164. int res = VLC->townh->towns[scenarioOps->playerInfos[k->first].castle].primaryRes;
  1165. if(res == 127)
  1166. {
  1167. k->second.resources[Res::WOOD] += 5 + ran()%6;
  1168. k->second.resources[Res::ORE] += 5 + ran()%6;
  1169. }
  1170. else
  1171. {
  1172. k->second.resources[res] += 3 + ran()%4;
  1173. }
  1174. break;
  1175. }
  1176. case PlayerSettings::bartifact:
  1177. {
  1178. if(!k->second.heroes.size())
  1179. {
  1180. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1181. break;
  1182. }
  1183. CArtifact *toGive;
  1184. toGive = VLC->arth->artifacts[VLC->arth->getRandomArt (CArtifact::ART_TREASURE)];
  1185. CGHeroInstance *hero = k->second.heroes[0];
  1186. giveHeroArtifact(hero, toGive->id);
  1187. }
  1188. break;
  1189. }
  1190. }
  1191. /****************************TOWNS************************************************/
  1192. tlog4 << "\tTowns";
  1193. for ( int i=0; i<4; i++)
  1194. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  1195. for (ui32 i=0;i<map->towns.size();i++)
  1196. {
  1197. CGTownInstance * vti =(map->towns[i]);
  1198. if(!vti->town)
  1199. vti->town = &VLC->townh->towns[vti->subID];
  1200. if (vti->name.length()==0) // if town hasn't name we draw it
  1201. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1202. //init buildings
  1203. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1204. {
  1205. vti->builtBuildings.erase(-50);
  1206. vti->builtBuildings.insert(EBuilding::VILLAGE_HALL);
  1207. vti->builtBuildings.insert(EBuilding::TAVERN);
  1208. vti->builtBuildings.insert(EBuilding::DWELL_FIRST);
  1209. if(ran()%2)
  1210. vti->builtBuildings.insert(EBuilding::DWELL_FIRST+1);
  1211. }
  1212. if (vstd::contains(vti->builtBuildings, EBuilding::SHIPYARD) && vti->state()==IBoatGenerator::TILE_BLOCKED)
  1213. vti->builtBuildings.erase(EBuilding::SHIPYARD);//if we have harbor without water - erase it (this is H3 behaviour)
  1214. //init hordes
  1215. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1216. if (vstd::contains(vti->builtBuildings,(-31-i))) //if we have horde for this level
  1217. {
  1218. vti->builtBuildings.erase(-31-i);//remove old ID
  1219. if (vti->town->hordeLvl[0] == i)//if town first horde is this one
  1220. {
  1221. vti->builtBuildings.insert(EBuilding::HORDE_1);//add it
  1222. if (vstd::contains(vti->builtBuildings,(EBuilding::DWELL_UP_FIRST+i)))//if we have upgraded dwelling as well
  1223. vti->builtBuildings.insert(EBuilding::HORDE_1_UPGR);//add it as well
  1224. }
  1225. if (vti->town->hordeLvl[1] == i)//if town second horde is this one
  1226. {
  1227. vti->builtBuildings.insert(EBuilding::HORDE_2);
  1228. if (vstd::contains(vti->builtBuildings,(EBuilding::DWELL_UP_FIRST+i)))
  1229. vti->builtBuildings.insert(EBuilding::HORDE_2_UPGR);
  1230. }
  1231. }
  1232. //town events
  1233. BOOST_FOREACH(CCastleEvent *ev, vti->events)
  1234. {
  1235. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1236. if (vstd::contains(ev->buildings,(-31-i))) //if we have horde for this level
  1237. {
  1238. ev->buildings.erase(-31-i);
  1239. if (vti->town->hordeLvl[0] == i)
  1240. ev->buildings.insert(EBuilding::HORDE_1);
  1241. if (vti->town->hordeLvl[1] == i)
  1242. ev->buildings.insert(EBuilding::HORDE_2);
  1243. }
  1244. }
  1245. //init spells
  1246. vti->spells.resize(GameConstants::SPELL_LEVELS);
  1247. CSpell *s;
  1248. for(ui32 z=0; z<vti->obligatorySpells.size();z++)
  1249. {
  1250. s = VLC->spellh->spells[vti->obligatorySpells[z]];
  1251. vti->spells[s->level-1].push_back(s->id);
  1252. vti->possibleSpells -= s->id;
  1253. }
  1254. while(vti->possibleSpells.size())
  1255. {
  1256. ui32 total=0;
  1257. int sel = -1;
  1258. for(ui32 ps=0;ps<vti->possibleSpells.size();ps++)
  1259. total += VLC->spellh->spells[vti->possibleSpells[ps]]->probabilities[vti->subID];
  1260. int r = (total)? ran()%total : -1;
  1261. for(ui32 ps=0; ps<vti->possibleSpells.size();ps++)
  1262. {
  1263. r -= VLC->spellh->spells[vti->possibleSpells[ps]]->probabilities[vti->subID];
  1264. if(r<0)
  1265. {
  1266. sel = ps;
  1267. break;
  1268. }
  1269. }
  1270. if(sel<0)
  1271. sel=0;
  1272. CSpell *s = VLC->spellh->spells[vti->possibleSpells[sel]];
  1273. vti->spells[s->level-1].push_back(s->id);
  1274. vti->possibleSpells -= s->id;
  1275. }
  1276. if(vti->getOwner() != 255)
  1277. getPlayer(vti->getOwner())->towns.push_back(vti);
  1278. }
  1279. //campaign bonuses for towns
  1280. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1281. {
  1282. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1283. if (chosenBonus.is_initialized() && chosenBonus->type == CScenarioTravel::STravelBonus::BUILDING)
  1284. {
  1285. for (int g=0; g<map->towns.size(); ++g)
  1286. {
  1287. PlayerState * owner = getPlayer(map->towns[g]->getOwner());
  1288. if (owner)
  1289. {
  1290. PlayerInfo & pi = map->players[owner->color];
  1291. if (owner->human && //human-owned
  1292. map->towns[g]->pos == pi.posOfMainTown + int3(2, 0, 0))
  1293. {
  1294. map->towns[g]->builtBuildings.insert(
  1295. CBuildingHandler::campToERMU(chosenBonus->info1, map->towns[g]->town->typeID, map->towns[g]->builtBuildings));
  1296. break;
  1297. }
  1298. }
  1299. }
  1300. }
  1301. }
  1302. tlog4 << "\tObject initialization";
  1303. objCaller->preInit();
  1304. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1305. {
  1306. obj->initObj();
  1307. if(obj->ID == Obj::PRISON) //prison also needs to initialize hero
  1308. static_cast<CGHeroInstance*>(obj)->initHero();
  1309. }
  1310. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1311. {
  1312. switch (obj->ID)
  1313. {
  1314. case Obj::QUEST_GUARD:
  1315. case Obj::SEER_HUT:
  1316. {
  1317. auto q = static_cast<CGSeerHut*>(obj);
  1318. assert (q);
  1319. q->setObjToKill();
  1320. }
  1321. }
  1322. }
  1323. CGTeleport::postInit(); //pairing subterranean gates
  1324. buildBonusSystemTree();
  1325. for(auto k=players.begin(); k!=players.end(); ++k)
  1326. {
  1327. if(k->first==255)
  1328. continue;
  1329. //init visiting and garrisoned heroes
  1330. BOOST_FOREACH(CGHeroInstance *h, k->second.heroes)
  1331. {
  1332. BOOST_FOREACH(CGTownInstance *t, k->second.towns)
  1333. {
  1334. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1335. if(vistile == h->pos || h->pos==t->pos)
  1336. {
  1337. t->setVisitingHero(h);
  1338. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1339. {
  1340. map->removeBlockVisTiles(h);
  1341. h->pos.x -= 1;
  1342. map->addBlockVisTiles(h);
  1343. }
  1344. break;
  1345. }
  1346. }
  1347. }
  1348. }
  1349. tlog4 << "\tChecking objectives";
  1350. map->checkForObjectives(); //needs to be run when all objects are properly placed
  1351. int seedAfterInit = ran();
  1352. tlog0 << "Seed after init is " << seedAfterInit << " (before was " << scenarioOps->seedToBeUsed << ")" << std::endl;
  1353. if(scenarioOps->seedPostInit > 0)
  1354. {
  1355. //RNG must be in the same state on all machines when initialization is done (otherwise we have desync)
  1356. assert(scenarioOps->seedPostInit == seedAfterInit);
  1357. }
  1358. else
  1359. {
  1360. scenarioOps->seedPostInit = seedAfterInit; //store the post init "seed"
  1361. }
  1362. }
  1363. void CGameState::initDuel()
  1364. {
  1365. DuelParameters dp;
  1366. try //CLoadFile likes throwing
  1367. {
  1368. if(boost::algorithm::ends_with(scenarioOps->mapname, ".json"))
  1369. {
  1370. tlog0 << "Loading duel settings from JSON file: " << scenarioOps->mapname << std::endl;
  1371. dp = DuelParameters::fromJSON(scenarioOps->mapname);
  1372. tlog0 << "JSON file has been successfully read!\n";
  1373. }
  1374. else
  1375. {
  1376. CLoadFile lf(scenarioOps->mapname);
  1377. lf >> dp;
  1378. }
  1379. }
  1380. catch(...)
  1381. {
  1382. tlog1 << "Cannot load duel settings from " << scenarioOps->mapname << std::endl;
  1383. throw;
  1384. }
  1385. const CArmedInstance *armies[2] = {0};
  1386. const CGHeroInstance *heroes[2] = {0};
  1387. CGTownInstance *town = NULL;
  1388. for(int i = 0; i < 2; i++)
  1389. {
  1390. CArmedInstance *obj = NULL;
  1391. if(dp.sides[i].heroId >= 0)
  1392. {
  1393. const DuelParameters::SideSettings &ss = dp.sides[i];
  1394. CGHeroInstance *h = new CGHeroInstance();
  1395. armies[i] = heroes[i] = h;
  1396. obj = h;
  1397. h->subID = ss.heroId;
  1398. for(int i = 0; i < ss.heroPrimSkills.size(); i++)
  1399. h->pushPrimSkill(i, ss.heroPrimSkills[i]);
  1400. if(ss.spells.size())
  1401. {
  1402. h->putArtifact(ArtifactPosition::SPELLBOOK, CArtifactInstance::createNewArtifactInstance(0));
  1403. boost::copy(ss.spells, std::inserter(h->spells, h->spells.begin()));
  1404. }
  1405. BOOST_FOREACH(auto &parka, ss.artifacts)
  1406. {
  1407. h->putArtifact(parka.first, parka.second);
  1408. }
  1409. typedef const std::pair<si32, si8> &TSecSKill;
  1410. BOOST_FOREACH(TSecSKill secSkill, ss.heroSecSkills)
  1411. h->setSecSkillLevel((CGHeroInstance::SecondarySkill)secSkill.first, secSkill.second, 1);
  1412. h->initHero(h->subID);
  1413. obj->initObj();
  1414. }
  1415. else
  1416. {
  1417. CGCreature *c = new CGCreature();
  1418. armies[i] = obj = c;
  1419. //c->subID = 34;
  1420. }
  1421. obj->setOwner(i);
  1422. for(int j = 0; j < ARRAY_COUNT(dp.sides[i].stacks); j++)
  1423. {
  1424. TCreature cre = dp.sides[i].stacks[j].type;
  1425. TQuantity count = dp.sides[i].stacks[j].count;
  1426. if(count || obj->hasStackAtSlot(j))
  1427. obj->setCreature(j, cre, count);
  1428. }
  1429. BOOST_FOREACH(const DuelParameters::CusomCreature &cc, dp.creatures)
  1430. {
  1431. CCreature *c = VLC->creh->creatures[cc.id];
  1432. if(cc.attack >= 0)
  1433. c->getBonusLocalFirst(Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK))->val = cc.attack;
  1434. if(cc.defense >= 0)
  1435. c->getBonusLocalFirst(Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE))->val = cc.defense;
  1436. if(cc.speed >= 0)
  1437. c->getBonusLocalFirst(Selector::type(Bonus::STACKS_SPEED))->val = cc.speed;
  1438. if(cc.HP >= 0)
  1439. c->getBonusLocalFirst(Selector::type(Bonus::STACK_HEALTH))->val = cc.HP;
  1440. if(cc.dmg >= 0)
  1441. {
  1442. c->getBonusLocalFirst(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1))->val = cc.dmg;
  1443. c->getBonusLocalFirst(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2))->val = cc.dmg;
  1444. }
  1445. if(cc.shoots >= 0)
  1446. c->getBonusLocalFirst(Selector::type(Bonus::SHOTS))->val = cc.shoots;
  1447. }
  1448. }
  1449. curB = BattleInfo::setupBattle(int3(), dp.bfieldType, dp.terType, armies, heroes, false, town);
  1450. curB->obstacles = dp.obstacles;
  1451. curB->localInit();
  1452. return;
  1453. }
  1454. int CGameState::battleGetBattlefieldType(int3 tile) const
  1455. {
  1456. if(tile==int3() && curB)
  1457. tile = curB->tile;
  1458. else if(tile==int3() && !curB)
  1459. return -1;
  1460. const TerrainTile &t = map->getTile(tile);
  1461. //fight in mine -> subterranean
  1462. if(dynamic_cast<const CGMine *>(t.visitableObjects.front()))
  1463. return 12;
  1464. BOOST_FOREACH(auto &obj, map->objects)
  1465. {
  1466. //look only for objects covering given tile
  1467. if( !obj || obj->pos.z != tile.z
  1468. || !obj->coveringAt(tile.x - obj->pos.x, tile.y - obj->pos.y))
  1469. continue;
  1470. switch(obj->ID)
  1471. {
  1472. case Obj::CLOVER_FIELD:
  1473. return 19;
  1474. case Obj::CURSED_GROUND1: case Obj::CURSED_GROUND2:
  1475. return 22;
  1476. case Obj::EVIL_FOG:
  1477. return 20;
  1478. case Obj::FAVORABLE_WINDS:
  1479. return 21;
  1480. case Obj::FIERY_FIELDS:
  1481. return 14;
  1482. case Obj::HOLY_GROUNDS:
  1483. return 18;
  1484. case Obj::LUCID_POOLS:
  1485. return 17;
  1486. case Obj::MAGIC_CLOUDS:
  1487. return 16;
  1488. case Obj::MAGIC_PLAINS1: case Obj::MAGIC_PLAINS2:
  1489. return 9;
  1490. case Obj::ROCKLANDS:
  1491. return 15;
  1492. }
  1493. }
  1494. if(!t.isWater() && t.isCoastal())
  1495. return 1; //sand/beach
  1496. switch(t.tertype)
  1497. {
  1498. case TerrainTile::dirt:
  1499. return rand()%3+3;
  1500. case TerrainTile::sand:
  1501. return 2; //TODO: coast support
  1502. case TerrainTile::grass:
  1503. return rand()%2+6;
  1504. case TerrainTile::snow:
  1505. return rand()%2+10;
  1506. case TerrainTile::swamp:
  1507. return 13;
  1508. case TerrainTile::rough:
  1509. return 23;
  1510. case TerrainTile::subterranean:
  1511. return 12;
  1512. case TerrainTile::lava:
  1513. return 8;
  1514. case TerrainTile::water:
  1515. return 25;
  1516. case TerrainTile::rock:
  1517. return 15;
  1518. default:
  1519. return -1;
  1520. }
  1521. }
  1522. UpgradeInfo CGameState::getUpgradeInfo(const CStackInstance &stack)
  1523. {
  1524. UpgradeInfo ret;
  1525. const CCreature *base = stack.type;
  1526. const CGHeroInstance *h = stack.armyObj->ID == Obj::HERO ? static_cast<const CGHeroInstance*>(stack.armyObj) : NULL;
  1527. const CGTownInstance *t = NULL;
  1528. if(stack.armyObj->ID == Obj::TOWN)
  1529. t = static_cast<const CGTownInstance *>(stack.armyObj);
  1530. else if(h)
  1531. { //hero speciality
  1532. TBonusListPtr lista = h->speciality.getBonuses(Selector::typeSubtype(Bonus::SPECIAL_UPGRADE, base->idNumber));
  1533. BOOST_FOREACH(const Bonus *it, *lista)
  1534. {
  1535. ui16 nid = it->additionalInfo;
  1536. if (nid != base->idNumber) //in very specific case the upgrade is available by default (?)
  1537. {
  1538. ret.newID.push_back(nid);
  1539. ret.cost.push_back(VLC->creh->creatures[nid]->cost - base->cost);
  1540. }
  1541. }
  1542. t = h->visitedTown;
  1543. }
  1544. if(t)
  1545. {
  1546. BOOST_FOREACH(const CGTownInstance::TCreaturesSet::value_type & dwelling, t->creatures)
  1547. {
  1548. if (vstd::contains(dwelling.second, base->idNumber)) //Dwelling with our creature
  1549. {
  1550. BOOST_FOREACH(ui32 upgrID, dwelling.second)
  1551. {
  1552. if(vstd::contains(base->upgrades, upgrID)) //possible upgrade
  1553. {
  1554. ret.newID.push_back(upgrID);
  1555. ret.cost.push_back(VLC->creh->creatures[upgrID]->cost - base->cost);
  1556. }
  1557. }
  1558. }
  1559. }
  1560. }
  1561. //hero is visiting Hill Fort
  1562. if(h && map->getTile(h->visitablePos()).visitableObjects.front()->ID == 35)
  1563. {
  1564. static const int costModifiers[] = {0, 25, 50, 75, 100}; //we get cheaper upgrades depending on level
  1565. const int costModifier = costModifiers[std::min<int>(std::max((int)base->level - 1, 0), ARRAY_COUNT(costModifiers) - 1)];
  1566. BOOST_FOREACH(si32 nid, base->upgrades)
  1567. {
  1568. ret.newID.push_back(nid);
  1569. ret.cost.push_back((VLC->creh->creatures[nid]->cost - base->cost) * costModifier / 100);
  1570. }
  1571. }
  1572. if(ret.newID.size())
  1573. ret.oldID = base->idNumber;
  1574. return ret;
  1575. }
  1576. int CGameState::getPlayerRelations( ui8 color1, ui8 color2 )
  1577. {
  1578. if ( color1 == color2 )
  1579. return 2;
  1580. if(color1 == 255 || color2 == 255) //neutral player has no friends
  1581. return 0;
  1582. const TeamState * ts = getPlayerTeam(color1);
  1583. if (ts && vstd::contains(ts->players, color2))
  1584. return 1;
  1585. return 0;
  1586. }
  1587. void CGameState::loadTownDInfos()
  1588. {
  1589. int i;
  1590. const JsonNode config(ResourceID("config/towns_defs.json"));
  1591. assert(config["town_defnames"].Vector().size() == GameConstants::F_NUMBER);
  1592. i = 0;
  1593. BOOST_FOREACH(const JsonNode &t, config["town_defnames"].Vector())
  1594. {
  1595. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1596. villages[i]->name = t["village"].String();
  1597. map->defy.push_back(villages[i]);
  1598. forts[i] = VLC->dobjinfo->castles[i];
  1599. map->defy.push_back(forts[i]);
  1600. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1601. capitols[i]->name = t["capitol"].String();
  1602. map->defy.push_back(capitols[i]);
  1603. ++i;
  1604. }
  1605. }
  1606. void CGameState::getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing)
  1607. {
  1608. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1609. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1610. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1611. {
  1612. const int3 hlp = tile + dirs[i];
  1613. if(!map->isInTheMap(hlp))
  1614. continue;
  1615. const TerrainTile &hlpt = map->getTile(hlp);
  1616. // //we cannot visit things from blocked tiles
  1617. // if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  1618. // {
  1619. // continue;
  1620. // }
  1621. if(srct.tertype == TerrainTile::water && limitCoastSailing && hlpt.tertype == TerrainTile::water && dirs[i].x && dirs[i].y) //diagonal move through water
  1622. {
  1623. int3 hlp1 = tile,
  1624. hlp2 = tile;
  1625. hlp1.x += dirs[i].x;
  1626. hlp2.y += dirs[i].y;
  1627. if(map->getTile(hlp1).tertype != TerrainTile::water || map->getTile(hlp2).tertype != TerrainTile::water)
  1628. continue;
  1629. }
  1630. if((indeterminate(onLand) || onLand == (hlpt.tertype!=TerrainTile::water) )
  1631. && hlpt.tertype != TerrainTile::rock)
  1632. {
  1633. vec.push_back(hlp);
  1634. }
  1635. }
  1636. }
  1637. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  1638. {
  1639. if(src == dest) //same tile
  1640. return 0;
  1641. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1642. &d = map->terrain[dest.x][dest.y][dest.z];
  1643. //get basic cost
  1644. int ret = h->getTileCost(d,s);
  1645. if(d.blocked && h->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  1646. {
  1647. bool freeFlying = h->getBonusesCount(Selector::typeSubtype(Bonus::FLYING_MOVEMENT, 1)) > 0;
  1648. if(!freeFlying)
  1649. {
  1650. ret *= 1.4; //40% penalty for movement over blocked tile
  1651. }
  1652. }
  1653. else if (d.tertype == TerrainTile::water)
  1654. {
  1655. if(h->boat && s.hasFavourableWinds() && d.hasFavourableWinds()) //Favourable Winds
  1656. ret *= 0.666;
  1657. else if (!h->boat && h->getBonusesCount(Selector::typeSubtype(Bonus::WATER_WALKING, 1)) > 0)
  1658. ret *= 1.4; //40% penalty for water walking
  1659. }
  1660. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1661. {
  1662. int old = ret;
  1663. ret *= 1.414213;
  1664. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1665. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1666. {
  1667. return remainingMovePoints;
  1668. }
  1669. }
  1670. int left = remainingMovePoints-ret;
  1671. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1672. {
  1673. std::vector<int3> vec;
  1674. getNeighbours(d, dest, vec, s.tertype != TerrainTile::water, true);
  1675. for(size_t i=0; i < vec.size(); i++)
  1676. {
  1677. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1678. if(fcost <= left)
  1679. {
  1680. return ret;
  1681. }
  1682. }
  1683. ret = remainingMovePoints;
  1684. }
  1685. return ret;
  1686. }
  1687. void CGameState::apply(CPack *pack)
  1688. {
  1689. ui16 typ = typeList.getTypeID(pack);
  1690. applierGs->apps[typ]->applyOnGS(this,pack);
  1691. }
  1692. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1693. {
  1694. //the old pathfinder is not supported anymore!
  1695. assert(0);
  1696. return false;
  1697. }
  1698. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  1699. {
  1700. CPathfinder pathfinder(out, this, hero);
  1701. pathfinder.calculatePaths(src, movement);
  1702. }
  1703. /**
  1704. * Tells if the tile is guarded by a monster as well as the position
  1705. * of the monster that will attack on it.
  1706. *
  1707. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  1708. * the monster guarding the tile.
  1709. */
  1710. int3 CGameState::guardingCreaturePosition (int3 pos) const
  1711. {
  1712. const int3 originalPos = pos;
  1713. // Give monster at position priority.
  1714. if (!map->isInTheMap(pos))
  1715. return int3(-1, -1, -1);
  1716. const TerrainTile &posTile = map->terrain[pos.x][pos.y][pos.z];
  1717. if (posTile.visitable)
  1718. {
  1719. BOOST_FOREACH (CGObjectInstance* obj, posTile.visitableObjects)
  1720. {
  1721. if(obj->blockVisit)
  1722. {
  1723. if (obj->ID == 54) // Monster
  1724. return pos;
  1725. else
  1726. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  1727. }
  1728. }
  1729. }
  1730. // See if there are any monsters adjacent.
  1731. pos -= int3(1, 1, 0); // Start with top left.
  1732. for (int dx = 0; dx < 3; dx++)
  1733. {
  1734. for (int dy = 0; dy < 3; dy++)
  1735. {
  1736. if (map->isInTheMap(pos))
  1737. {
  1738. TerrainTile &tile = map->terrain[pos.x][pos.y][pos.z];
  1739. if (tile.visitable && (tile.tertype == TerrainTile::water) == (posTile.tertype == TerrainTile::water))
  1740. {
  1741. BOOST_FOREACH (CGObjectInstance* obj, tile.visitableObjects)
  1742. {
  1743. if (obj->ID == 54 && checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1744. {
  1745. return pos;
  1746. }
  1747. }
  1748. }
  1749. }
  1750. pos.y++;
  1751. }
  1752. pos.y -= 3;
  1753. pos.x++;
  1754. }
  1755. return int3(-1, -1, -1);
  1756. }
  1757. bool CGameState::isVisible(int3 pos, int player)
  1758. {
  1759. if(player == 255) //neutral player
  1760. return false;
  1761. return getPlayerTeam(player)->fogOfWarMap[pos.x][pos.y][pos.z];
  1762. }
  1763. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  1764. {
  1765. if(player == -1)
  1766. return true;
  1767. if(player == 255) //neutral player -> TODO ??? needed?
  1768. return false;
  1769. //object is visible when at least one blocked tile is visible
  1770. for(int fx=0; fx<8; ++fx)
  1771. {
  1772. for(int fy=0; fy<6; ++fy)
  1773. {
  1774. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  1775. if(map->isInTheMap(pos)
  1776. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  1777. && isVisible(pos, player) )
  1778. return true;
  1779. }
  1780. }
  1781. return false;
  1782. }
  1783. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1784. {
  1785. const TerrainTile * pom = &map->getTile(dst);
  1786. return checkForVisitableDir(src, pom, dst);
  1787. }
  1788. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  1789. {
  1790. for(ui32 b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  1791. {
  1792. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  1793. continue;
  1794. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  1795. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  1796. {
  1797. return false;
  1798. }
  1799. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  1800. {
  1801. return false;
  1802. }
  1803. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  1804. {
  1805. return false;
  1806. }
  1807. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  1808. {
  1809. return false;
  1810. }
  1811. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  1812. {
  1813. return false;
  1814. }
  1815. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  1816. {
  1817. return false;
  1818. }
  1819. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  1820. {
  1821. return false;
  1822. }
  1823. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  1824. {
  1825. return false;
  1826. }
  1827. }
  1828. return true;
  1829. }
  1830. int CGameState::victoryCheck( ui8 player ) const
  1831. {
  1832. const PlayerState *p = CGameInfoCallback::getPlayer(player);
  1833. if(map->victoryCondition.condition == EVictoryConditionType::WINSTANDARD || map->victoryCondition.allowNormalVictory
  1834. || (!p->human && !map->victoryCondition.appliesToAI)) //if the special victory condition applies only to human, AI has the standard)
  1835. {
  1836. if(player == checkForStandardWin())
  1837. return -1;
  1838. }
  1839. if (p->enteredWinningCheatCode)
  1840. { //cheater or tester, but has entered the code...
  1841. if(map->victoryCondition.condition == EVictoryConditionType::WINSTANDARD)
  1842. return -1;
  1843. else
  1844. return 1;
  1845. }
  1846. if(p->human || map->victoryCondition.appliesToAI)
  1847. {
  1848. switch(map->victoryCondition.condition)
  1849. {
  1850. case EVictoryConditionType::ARTIFACT:
  1851. //check if any hero has winning artifact
  1852. for(size_t i = 0; i < p->heroes.size(); i++)
  1853. if(p->heroes[i]->hasArt(map->victoryCondition.ID))
  1854. return 1;
  1855. break;
  1856. case EVictoryConditionType::GATHERTROOP:
  1857. {
  1858. //check if in players armies there is enough creatures
  1859. int total = 0; //creature counter
  1860. for(size_t i = 0; i < map->objects.size(); i++)
  1861. {
  1862. const CArmedInstance *ai = NULL;
  1863. if(map->objects[i]
  1864. && map->objects[i]->tempOwner == player //object controlled by player
  1865. && (ai = dynamic_cast<const CArmedInstance*>(map->objects[i].get()))) //contains army
  1866. {
  1867. for(TSlots::const_iterator i=ai->Slots().begin(); i!=ai->Slots().end(); ++i) //iterate through army
  1868. if(i->second->type->idNumber == map->victoryCondition.ID) //it's searched creature
  1869. total += i->second->count;
  1870. }
  1871. }
  1872. if(total >= map->victoryCondition.count)
  1873. return 1;
  1874. }
  1875. break;
  1876. case EVictoryConditionType::GATHERRESOURCE:
  1877. if(p->resources[map->victoryCondition.ID] >= map->victoryCondition.count)
  1878. return 1;
  1879. break;
  1880. case EVictoryConditionType::BUILDCITY:
  1881. {
  1882. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  1883. if(t->tempOwner == player && t->fortLevel()-1 >= map->victoryCondition.ID && t->hallLevel()-1 >= map->victoryCondition.count)
  1884. return 1;
  1885. }
  1886. break;
  1887. case EVictoryConditionType::BUILDGRAIL:
  1888. BOOST_FOREACH(const CGTownInstance *t, map->towns)
  1889. if((t == map->victoryCondition.obj || !map->victoryCondition.obj)
  1890. && t->tempOwner == player
  1891. && t->hasBuilt(EBuilding::GRAIL))
  1892. return 1;
  1893. break;
  1894. case EVictoryConditionType::BEATHERO:
  1895. if(map->victoryCondition.obj->tempOwner >= GameConstants::PLAYER_LIMIT) //target hero not present on map
  1896. return 1;
  1897. break;
  1898. case EVictoryConditionType::CAPTURECITY:
  1899. {
  1900. if(map->victoryCondition.obj->tempOwner == player)
  1901. return 1;
  1902. }
  1903. break;
  1904. case EVictoryConditionType::BEATMONSTER:
  1905. if(!map->objects[map->victoryCondition.obj->id]) //target monster not present on map
  1906. return 1;
  1907. break;
  1908. case EVictoryConditionType::TAKEDWELLINGS:
  1909. for(size_t i = 0; i < map->objects.size(); i++)
  1910. {
  1911. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  1912. {
  1913. switch(map->objects[i]->ID)
  1914. {
  1915. case 17: case 18: case 19: case 20: //dwellings
  1916. case 216: case 217: case 218:
  1917. return 0; //found not flagged dwelling - player not won
  1918. }
  1919. }
  1920. }
  1921. return 1;
  1922. break;
  1923. case EVictoryConditionType::TAKEMINES:
  1924. for(size_t i = 0; i < map->objects.size(); i++)
  1925. {
  1926. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  1927. {
  1928. switch(map->objects[i]->ID)
  1929. {
  1930. case 53: case 220:
  1931. return 0; //found not flagged mine - player not won
  1932. }
  1933. }
  1934. }
  1935. return 1;
  1936. break;
  1937. case EVictoryConditionType::TRANSPORTITEM:
  1938. {
  1939. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  1940. if((t->visitingHero && t->visitingHero->hasArt(map->victoryCondition.ID))
  1941. || (t->garrisonHero && t->garrisonHero->hasArt(map->victoryCondition.ID)))
  1942. {
  1943. return 1;
  1944. }
  1945. }
  1946. break;
  1947. }
  1948. }
  1949. return 0;
  1950. }
  1951. ui8 CGameState::checkForStandardWin() const
  1952. {
  1953. //std victory condition is:
  1954. //all enemies lost
  1955. TPlayerColor supposedWinner = 255, winnerTeam = 255;
  1956. for(auto i = players.begin(); i != players.end(); i++)
  1957. {
  1958. if(i->second.status == PlayerState::INGAME && i->first < GameConstants::PLAYER_LIMIT)
  1959. {
  1960. if(supposedWinner == 255)
  1961. {
  1962. //first player remaining ingame - candidate for victory
  1963. supposedWinner = i->second.color;
  1964. winnerTeam = i->second.team;
  1965. }
  1966. else if(winnerTeam != i->second.team)
  1967. {
  1968. //current candidate has enemy remaining in game -> no vicotry
  1969. return 255;
  1970. }
  1971. }
  1972. }
  1973. return supposedWinner;
  1974. }
  1975. bool CGameState::checkForStandardLoss( ui8 player ) const
  1976. {
  1977. //std loss condition is: player lost all towns and heroes
  1978. const PlayerState &p = *CGameInfoCallback::getPlayer(player);
  1979. return !p.heroes.size() && !p.towns.size();
  1980. }
  1981. struct statsHLP
  1982. {
  1983. typedef std::pair< TPlayerColor, si64 > TStat;
  1984. //converts [<player's color, value>] to vec[place] -> platers
  1985. static std::vector< std::vector< TPlayerColor > > getRank( std::vector<TStat> stats )
  1986. {
  1987. std::sort(stats.begin(), stats.end(), statsHLP());
  1988. //put first element
  1989. std::vector< std::vector<TPlayerColor> > ret;
  1990. std::vector<TPlayerColor> tmp;
  1991. tmp.push_back( stats[0].first );
  1992. ret.push_back( tmp );
  1993. //the rest of elements
  1994. for(int g=1; g<stats.size(); ++g)
  1995. {
  1996. if(stats[g].second == stats[g-1].second)
  1997. {
  1998. (ret.end()-1)->push_back( stats[g].first );
  1999. }
  2000. else
  2001. {
  2002. //create next occupied rank
  2003. std::vector<TPlayerColor> tmp;
  2004. tmp.push_back(stats[g].first);
  2005. ret.push_back(tmp);
  2006. }
  2007. }
  2008. return ret;
  2009. }
  2010. bool operator()(const TStat & a, const TStat & b) const
  2011. {
  2012. return a.second > b.second;
  2013. }
  2014. static const CGHeroInstance * findBestHero(CGameState * gs, int color)
  2015. {
  2016. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  2017. if(!h.size())
  2018. return NULL;
  2019. //best hero will be that with highest exp
  2020. int best = 0;
  2021. for(int b=1; b<h.size(); ++b)
  2022. {
  2023. if(h[b]->exp > h[best]->exp)
  2024. {
  2025. best = b;
  2026. }
  2027. }
  2028. return h[best];
  2029. }
  2030. //calculates total number of artifacts that belong to given player
  2031. static int getNumberOfArts(const PlayerState * ps)
  2032. {
  2033. int ret = 0;
  2034. for(int g=0; g<ps->heroes.size(); ++g)
  2035. {
  2036. ret += ps->heroes[g]->artifactsInBackpack.size() + ps->heroes[g]->artifactsWorn.size();
  2037. }
  2038. return ret;
  2039. }
  2040. };
  2041. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  2042. {
  2043. #define FILL_FIELD(FIELD, VAL_GETTER) \
  2044. { \
  2045. std::vector< std::pair< TPlayerColor, si64 > > stats; \
  2046. for(auto g = players.begin(); g != players.end(); ++g) \
  2047. { \
  2048. if(g->second.color == 255) \
  2049. continue; \
  2050. std::pair< ui8, si64 > stat; \
  2051. stat.first = g->second.color; \
  2052. stat.second = VAL_GETTER; \
  2053. stats.push_back(stat); \
  2054. } \
  2055. tgi.FIELD = statsHLP::getRank(stats); \
  2056. }
  2057. for(auto g = players.begin(); g != players.end(); ++g)
  2058. {
  2059. if(g->second.color != 255)
  2060. tgi.playerColors.push_back(g->second.color);
  2061. }
  2062. if(level >= 1) //num of towns & num of heroes
  2063. {
  2064. //num of towns
  2065. FILL_FIELD(numOfTowns, g->second.towns.size())
  2066. //num of heroes
  2067. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2068. //best hero's portrait
  2069. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2070. {
  2071. if(g->second.color == 255)
  2072. continue;
  2073. const CGHeroInstance * best = statsHLP::findBestHero(this, g->second.color);
  2074. InfoAboutHero iah;
  2075. iah.initFromHero(best, level >= 8);
  2076. iah.army.clear();
  2077. tgi.colorToBestHero[g->second.color] = iah;
  2078. }
  2079. }
  2080. if(level >= 2) //gold
  2081. {
  2082. FILL_FIELD(gold, g->second.resources[Res::GOLD])
  2083. }
  2084. if(level >= 2) //wood & ore
  2085. {
  2086. FILL_FIELD(woodOre, g->second.resources[Res::WOOD] + g->second.resources[Res::ORE])
  2087. }
  2088. if(level >= 3) //mercury, sulfur, crystal, gems
  2089. {
  2090. FILL_FIELD(mercSulfCrystGems, g->second.resources[Res::MERCURY] + g->second.resources[Res::SULFUR] + g->second.resources[Res::CRYSTAL] + g->second.resources[Res::GEMS])
  2091. }
  2092. if(level >= 4) //obelisks found
  2093. {
  2094. //TODO
  2095. }
  2096. if(level >= 5) //artifacts
  2097. {
  2098. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  2099. }
  2100. if(level >= 6) //army strength
  2101. {
  2102. //TODO
  2103. }
  2104. if(level >= 7) //income
  2105. {
  2106. //TODO
  2107. }
  2108. if(level >= 8) //best hero's stats
  2109. {
  2110. //already set in lvl 1 handling
  2111. }
  2112. if(level >= 9) //personality
  2113. {
  2114. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2115. {
  2116. if(g->second.color == 255) //do nothing for neutral player
  2117. continue;
  2118. if(g->second.human)
  2119. {
  2120. tgi.personality[g->second.color] = -1;
  2121. }
  2122. else //AI
  2123. {
  2124. tgi.personality[g->second.color] = map->players[g->second.color].AITactic;
  2125. }
  2126. }
  2127. }
  2128. if(level >= 10) //best creature
  2129. {
  2130. //best creatures belonging to player (highest AI value)
  2131. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2132. {
  2133. if(g->second.color == 255) //do nothing for neutral player
  2134. continue;
  2135. int bestCre = -1; //best creature's ID
  2136. for(int b=0; b<g->second.heroes.size(); ++b)
  2137. {
  2138. for(TSlots::const_iterator it = g->second.heroes[b]->Slots().begin(); it != g->second.heroes[b]->Slots().end(); ++it)
  2139. {
  2140. int toCmp = it->second->type->idNumber; //ID of creature we should compare with the best one
  2141. if(bestCre == -1 || VLC->creh->creatures[bestCre]->AIValue < VLC->creh->creatures[toCmp]->AIValue)
  2142. {
  2143. bestCre = toCmp;
  2144. }
  2145. }
  2146. }
  2147. tgi.bestCreature[g->second.color] = bestCre;
  2148. }
  2149. }
  2150. #undef FILL_FIELD
  2151. }
  2152. int CGameState::lossCheck( ui8 player ) const
  2153. {
  2154. const PlayerState *p = CGameInfoCallback::getPlayer(player);
  2155. //if(map->lossCondition.typeOfLossCon == lossStandard)
  2156. if(checkForStandardLoss(player))
  2157. return -1;
  2158. if (p->enteredLosingCheatCode)
  2159. {
  2160. return 1;
  2161. }
  2162. if(p->human) //special loss condition applies only to human player
  2163. {
  2164. switch(map->lossCondition.typeOfLossCon)
  2165. {
  2166. case ELossConditionType::LOSSCASTLE:
  2167. {
  2168. const CGTownInstance *t = dynamic_cast<const CGTownInstance *>(map->lossCondition.obj);
  2169. assert(t);
  2170. if(t->tempOwner != player)
  2171. return 1;
  2172. }
  2173. break;
  2174. case ELossConditionType::LOSSHERO:
  2175. {
  2176. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(map->lossCondition.obj);
  2177. assert(h);
  2178. if(h->tempOwner != player)
  2179. return 1;
  2180. }
  2181. break;
  2182. case ELossConditionType::TIMEEXPIRES:
  2183. if(map->lossCondition.timeLimit < day)
  2184. return 1;
  2185. break;
  2186. }
  2187. }
  2188. if(!p->towns.size() && p->daysWithoutCastle >= 7)
  2189. return 2;
  2190. return false;
  2191. }
  2192. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > CGameState::unusedHeroesFromPool()
  2193. {
  2194. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > pool = hpool.heroesPool;
  2195. for ( auto i = players.cbegin() ; i != players.cend();i++)
  2196. for(auto j = i->second.availableHeroes.cbegin(); j != i->second.availableHeroes.cend(); j++)
  2197. if(*j)
  2198. pool.erase((**j).subID);
  2199. return pool;
  2200. }
  2201. void CGameState::buildBonusSystemTree()
  2202. {
  2203. buildGlobalTeamPlayerTree();
  2204. attachArmedObjects();
  2205. BOOST_FOREACH(CGTownInstance *t, map->towns)
  2206. {
  2207. t->deserializationFix();
  2208. }
  2209. // CStackInstance <-> CCreature, CStackInstance <-> CArmedInstance, CArtifactInstance <-> CArtifact
  2210. // are provided on initializing / deserializing
  2211. }
  2212. void CGameState::deserializationFix()
  2213. {
  2214. buildGlobalTeamPlayerTree();
  2215. attachArmedObjects();
  2216. }
  2217. void CGameState::buildGlobalTeamPlayerTree()
  2218. {
  2219. for(auto k=teams.begin(); k!=teams.end(); ++k)
  2220. {
  2221. TeamState *t = &k->second;
  2222. t->attachTo(&globalEffects);
  2223. BOOST_FOREACH(ui8 teamMember, k->second.players)
  2224. {
  2225. PlayerState *p = getPlayer(teamMember);
  2226. assert(p);
  2227. p->attachTo(t);
  2228. }
  2229. }
  2230. }
  2231. void CGameState::attachArmedObjects()
  2232. {
  2233. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  2234. {
  2235. if(CArmedInstance *armed = dynamic_cast<CArmedInstance*>(obj))
  2236. armed->whatShouldBeAttached()->attachTo(armed->whereShouldBeAttached(this));
  2237. }
  2238. }
  2239. void CGameState::giveHeroArtifact(CGHeroInstance *h, int aid)
  2240. {
  2241. CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  2242. CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  2243. map->addNewArtifactInstance(ai);
  2244. ai->putAt(ArtifactLocation(h, ai->firstAvailableSlot(h)));
  2245. }
  2246. int3 CPath::startPos() const
  2247. {
  2248. return nodes[nodes.size()-1].coord;
  2249. }
  2250. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  2251. {
  2252. if (mode==0)
  2253. {
  2254. for (ui32 i=0;i<nodes.size();i++)
  2255. {
  2256. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2257. }
  2258. }
  2259. }
  2260. int3 CPath::endPos() const
  2261. {
  2262. return nodes[0].coord;
  2263. }
  2264. CGPathNode::CGPathNode()
  2265. :coord(-1,-1,-1)
  2266. {
  2267. accessible = 0;
  2268. land = 0;
  2269. moveRemains = 0;
  2270. turns = 255;
  2271. theNodeBefore = NULL;
  2272. }
  2273. bool CGPathNode::reachable() const
  2274. {
  2275. return turns < 255;
  2276. }
  2277. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  2278. {
  2279. assert(isValid);
  2280. out.nodes.clear();
  2281. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  2282. if(!curnode->theNodeBefore)
  2283. return false;
  2284. while(curnode)
  2285. {
  2286. CGPathNode cpn = *curnode;
  2287. curnode = curnode->theNodeBefore;
  2288. out.nodes.push_back(cpn);
  2289. }
  2290. return true;
  2291. }
  2292. CPathsInfo::CPathsInfo( const int3 &Sizes )
  2293. :sizes(Sizes)
  2294. {
  2295. hero = NULL;
  2296. nodes = new CGPathNode**[sizes.x];
  2297. for(int i = 0; i < sizes.x; i++)
  2298. {
  2299. nodes[i] = new CGPathNode*[sizes.y];
  2300. for (int j = 0; j < sizes.y; j++)
  2301. {
  2302. nodes[i][j] = new CGPathNode[sizes.z];
  2303. }
  2304. }
  2305. }
  2306. CPathsInfo::~CPathsInfo()
  2307. {
  2308. for(int i = 0; i < sizes.x; i++)
  2309. {
  2310. for (int j = 0; j < sizes.y; j++)
  2311. {
  2312. delete [] nodes[i][j];
  2313. }
  2314. delete [] nodes[i];
  2315. }
  2316. delete [] nodes;
  2317. }
  2318. int3 CGPath::startPos() const
  2319. {
  2320. return nodes[nodes.size()-1].coord;
  2321. }
  2322. int3 CGPath::endPos() const
  2323. {
  2324. return nodes[0].coord;
  2325. }
  2326. void CGPath::convert( ui8 mode )
  2327. {
  2328. if(mode==0)
  2329. {
  2330. for(ui32 i=0;i<nodes.size();i++)
  2331. {
  2332. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2333. }
  2334. }
  2335. }
  2336. PlayerState::PlayerState()
  2337. : color(-1), currentSelection(0xffffffff), enteredWinningCheatCode(0),
  2338. enteredLosingCheatCode(0), status(INGAME), daysWithoutCastle(0)
  2339. {
  2340. setNodeType(PLAYER);
  2341. }
  2342. std::string PlayerState::nodeName() const
  2343. {
  2344. return "Player " + (color < VLC->generaltexth->capColors.size() ? VLC->generaltexth->capColors[color] : boost::lexical_cast<std::string>(color));
  2345. }
  2346. // void PlayerState::getParents(TCNodes &out, const CBonusSystemNode *root /*= NULL*/) const
  2347. // {
  2348. // return; //no loops possible
  2349. // }
  2350. //
  2351. // void PlayerState::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  2352. // {
  2353. // for (std::vector<CGHeroInstance *>::const_iterator it = heroes.begin(); it != heroes.end(); it++)
  2354. // {
  2355. // if (*it != root)
  2356. // (*it)->getBonuses(out, selector, this);
  2357. // }
  2358. // }
  2359. InfoAboutArmy::InfoAboutArmy():
  2360. owner(GameConstants::NEUTRAL_PLAYER)
  2361. {}
  2362. InfoAboutArmy::InfoAboutArmy(const CArmedInstance *Army, bool detailed)
  2363. {
  2364. initFromArmy(Army, detailed);
  2365. }
  2366. void InfoAboutArmy::initFromArmy(const CArmedInstance *Army, bool detailed)
  2367. {
  2368. army = ArmyDescriptor(Army, detailed);
  2369. owner = Army->tempOwner;
  2370. name = Army->getHoverText();
  2371. }
  2372. void InfoAboutHero::assign(const InfoAboutHero & iah)
  2373. {
  2374. InfoAboutArmy::operator = (iah);
  2375. details = (iah.details ? new Details(*iah.details) : NULL);
  2376. hclass = iah.hclass;
  2377. portrait = iah.portrait;
  2378. }
  2379. InfoAboutHero::InfoAboutHero():
  2380. details(nullptr),
  2381. hclass(nullptr),
  2382. portrait(-1)
  2383. {}
  2384. InfoAboutHero::InfoAboutHero(const InfoAboutHero & iah):
  2385. InfoAboutArmy()
  2386. {
  2387. assign(iah);
  2388. }
  2389. InfoAboutHero::InfoAboutHero(const CGHeroInstance *h, bool detailed)
  2390. {
  2391. initFromHero(h, detailed);
  2392. }
  2393. InfoAboutHero::~InfoAboutHero()
  2394. {
  2395. delete details;
  2396. }
  2397. InfoAboutHero & InfoAboutHero::operator=(const InfoAboutHero & iah)
  2398. {
  2399. assign(iah);
  2400. return *this;
  2401. }
  2402. void InfoAboutHero::initFromHero(const CGHeroInstance *h, bool detailed)
  2403. {
  2404. if(!h)
  2405. return;
  2406. initFromArmy(h, detailed);
  2407. hclass = h->type->heroClass;
  2408. name = h->name;
  2409. portrait = h->portrait;
  2410. if(detailed)
  2411. {
  2412. //include details about hero
  2413. details = new Details;
  2414. details->luck = h->LuckVal();
  2415. details->morale = h->MoraleVal();
  2416. details->mana = h->mana;
  2417. details->primskills.resize(GameConstants::PRIMARY_SKILLS);
  2418. for (int i = 0; i < GameConstants::PRIMARY_SKILLS ; i++)
  2419. {
  2420. details->primskills[i] = h->getPrimSkillLevel(i);
  2421. }
  2422. }
  2423. }
  2424. InfoAboutTown::InfoAboutTown():
  2425. details(nullptr),
  2426. tType(nullptr),
  2427. built(0),
  2428. fortLevel(0)
  2429. {
  2430. }
  2431. InfoAboutTown::InfoAboutTown(const CGTownInstance *t, bool detailed)
  2432. {
  2433. initFromTown(t, detailed);
  2434. }
  2435. InfoAboutTown::~InfoAboutTown()
  2436. {
  2437. delete details;
  2438. }
  2439. void InfoAboutTown::initFromTown(const CGTownInstance *t, bool detailed)
  2440. {
  2441. initFromArmy(t, detailed);
  2442. army = ArmyDescriptor(t->getUpperArmy(), detailed);
  2443. built = t->builded;
  2444. fortLevel = t->fortLevel();
  2445. name = t->name;
  2446. tType = t->town;
  2447. if(detailed)
  2448. {
  2449. //include details about hero
  2450. details = new Details;
  2451. details->goldIncome = t->dailyIncome();
  2452. details->customRes = t->hasBuilt(EBuilding::RESOURCE_SILO);
  2453. details->hallLevel = t->hallLevel();
  2454. details->garrisonedHero = t->garrisonHero;
  2455. }
  2456. }
  2457. ArmyDescriptor::ArmyDescriptor(const CArmedInstance *army, bool detailed)
  2458. : isDetailed(detailed)
  2459. {
  2460. for(TSlots::const_iterator i = army->Slots().begin(); i != army->Slots().end(); i++)
  2461. {
  2462. if(detailed)
  2463. (*this)[i->first] = *i->second;
  2464. else
  2465. (*this)[i->first] = CStackBasicDescriptor(i->second->type, i->second->getQuantityID());
  2466. }
  2467. }
  2468. ArmyDescriptor::ArmyDescriptor()
  2469. : isDetailed(false)
  2470. {
  2471. }
  2472. int ArmyDescriptor::getStrength() const
  2473. {
  2474. ui64 ret = 0;
  2475. if(isDetailed)
  2476. {
  2477. for(const_iterator i = begin(); i != end(); i++)
  2478. ret += i->second.type->AIValue * i->second.count;
  2479. }
  2480. else
  2481. {
  2482. for(const_iterator i = begin(); i != end(); i++)
  2483. ret += i->second.type->AIValue * CCreature::estimateCreatureCount(i->second.count);
  2484. }
  2485. return ret;
  2486. }
  2487. DuelParameters::SideSettings::StackSettings::StackSettings()
  2488. : type(-1), count(0)
  2489. {
  2490. }
  2491. DuelParameters::SideSettings::StackSettings::StackSettings(si32 Type, si32 Count)
  2492. : type(Type), count(Count)
  2493. {
  2494. }
  2495. DuelParameters::SideSettings::SideSettings()
  2496. {
  2497. heroId = -1;
  2498. }
  2499. DuelParameters::DuelParameters()
  2500. {
  2501. terType = TerrainTile::dirt;
  2502. bfieldType = 15;
  2503. }
  2504. DuelParameters DuelParameters::fromJSON(const std::string &fname)
  2505. {
  2506. DuelParameters ret;
  2507. const JsonNode duelData(ResourceID("DATA/" + fname, EResType::TEXT));
  2508. ret.terType = duelData["terType"].Float();
  2509. ret.bfieldType = duelData["bfieldType"].Float();
  2510. BOOST_FOREACH(const JsonNode &n, duelData["sides"].Vector())
  2511. {
  2512. SideSettings &ss = ret.sides[(int)n["side"].Float()];
  2513. int i = 0;
  2514. BOOST_FOREACH(const JsonNode &stackNode, n["army"].Vector())
  2515. {
  2516. ss.stacks[i].type = stackNode.Vector()[0].Float();
  2517. ss.stacks[i].count = stackNode.Vector()[1].Float();
  2518. i++;
  2519. }
  2520. if(n["heroid"].getType() == JsonNode::DATA_FLOAT)
  2521. ss.heroId = n["heroid"].Float();
  2522. else
  2523. ss.heroId = -1;
  2524. BOOST_FOREACH(const JsonNode &n, n["heroPrimSkills"].Vector())
  2525. ss.heroPrimSkills.push_back(n.Float());
  2526. BOOST_FOREACH(const JsonNode &skillNode, n["heroSecSkills"].Vector())
  2527. {
  2528. std::pair<si32, si8> secSkill;
  2529. secSkill.first = skillNode.Vector()[0].Float();
  2530. secSkill.second = skillNode.Vector()[1].Float();
  2531. ss.heroSecSkills.push_back(secSkill);
  2532. }
  2533. assert(ss.heroPrimSkills.empty() || ss.heroPrimSkills.size() == GameConstants::PRIMARY_SKILLS);
  2534. if(ss.heroId != -1)
  2535. {
  2536. const JsonNode & spells = n["spells"];
  2537. if(spells.getType() == JsonNode::DATA_STRING && spells.String() == "all")
  2538. {
  2539. BOOST_FOREACH(auto spell, VLC->spellh->spells)
  2540. if(spell->id <= Spells::SUMMON_AIR_ELEMENTAL)
  2541. ss.spells.insert(spell->id);
  2542. }
  2543. else
  2544. BOOST_FOREACH(const JsonNode &spell, n["spells"].Vector())
  2545. ss.spells.insert(spell.Float());
  2546. }
  2547. }
  2548. BOOST_FOREACH(const JsonNode &n, duelData["obstacles"].Vector())
  2549. {
  2550. auto oi = make_shared<CObstacleInstance>();
  2551. if(n.getType() == JsonNode::DATA_VECTOR)
  2552. {
  2553. oi->ID = n.Vector()[0].Float();
  2554. oi->pos = n.Vector()[1].Float();
  2555. }
  2556. else
  2557. {
  2558. assert(n.getType() == JsonNode::DATA_FLOAT);
  2559. oi->ID = 21;
  2560. oi->pos = n.Float();
  2561. }
  2562. oi->uniqueID = ret.obstacles.size();
  2563. ret.obstacles.push_back(oi);
  2564. }
  2565. BOOST_FOREACH(const JsonNode &n, duelData["creatures"].Vector())
  2566. {
  2567. CusomCreature cc;
  2568. cc.id = n["id"].Float();
  2569. #define retreive(name) \
  2570. if(n[ #name ].getType() == JsonNode::DATA_FLOAT)\
  2571. cc.name = n[ #name ].Float(); \
  2572. else \
  2573. cc.name = -1;
  2574. retreive(attack);
  2575. retreive(defense);
  2576. retreive(HP);
  2577. retreive(dmg);
  2578. retreive(shoots);
  2579. retreive(speed);
  2580. ret.creatures.push_back(cc);
  2581. }
  2582. return ret;
  2583. }
  2584. TeamState::TeamState()
  2585. {
  2586. setNodeType(TEAM);
  2587. }
  2588. void CPathfinder::initializeGraph()
  2589. {
  2590. CGPathNode ***graph = out.nodes;
  2591. for(size_t i=0; i < out.sizes.x; ++i)
  2592. {
  2593. for(size_t j=0; j < out.sizes.y; ++j)
  2594. {
  2595. for(size_t k=0; k < out.sizes.z; ++k)
  2596. {
  2597. curPos = int3(i,j,k);
  2598. const TerrainTile *tinfo = &gs->map->terrain[i][j][k];
  2599. CGPathNode &node = graph[i][j][k];
  2600. node.accessible = evaluateAccessibility(tinfo);
  2601. node.turns = 0xff;
  2602. node.moveRemains = 0;
  2603. node.coord.x = i;
  2604. node.coord.y = j;
  2605. node.coord.z = k;
  2606. node.land = tinfo->tertype != TerrainTile::water;
  2607. node.theNodeBefore = NULL;
  2608. }
  2609. }
  2610. }
  2611. }
  2612. void CPathfinder::calculatePaths(int3 src /*= int3(-1,-1,-1)*/, int movement /*= -1*/)
  2613. {
  2614. assert(hero);
  2615. assert(hero == getHero(hero->id));
  2616. if(src.x < 0)
  2617. src = hero->getPosition(false);
  2618. if(movement < 0)
  2619. movement = hero->movement;
  2620. out.hero = hero;
  2621. out.hpos = src;
  2622. if(!gs->map->isInTheMap(src)/* || !gs->map->isInTheMap(dest)*/) //check input
  2623. {
  2624. tlog1 << "CGameState::calculatePaths: Hero outside the gs->map? How dare you...\n";
  2625. return;
  2626. }
  2627. initializeGraph();
  2628. //initial tile - set cost on 0 and add to the queue
  2629. CGPathNode &initialNode = *getNode(src);
  2630. initialNode.turns = 0;
  2631. initialNode.moveRemains = movement;
  2632. mq.push_back(&initialNode);
  2633. std::vector<int3> neighbours;
  2634. neighbours.reserve(16);
  2635. while(!mq.empty())
  2636. {
  2637. cp = mq.front();
  2638. mq.pop_front();
  2639. const int3 sourceGuardPosition = guardingCreaturePosition(cp->coord);
  2640. bool guardedSource = (sourceGuardPosition != int3(-1, -1, -1) && cp->coord != src);
  2641. ct = &gs->map->getTile(cp->coord);
  2642. int movement = cp->moveRemains, turn = cp->turns;
  2643. if(!movement)
  2644. {
  2645. movement = hero->maxMovePoints(cp->land);
  2646. turn++;
  2647. }
  2648. //add accessible neighbouring nodes to the queue
  2649. neighbours.clear();
  2650. //handling subterranean gate => it's exit is the only neighbour
  2651. bool subterraneanEntry = (ct->topVisitableID() == Obj::SUBTERRANEAN_GATE && useSubterraneanGates);
  2652. if(subterraneanEntry)
  2653. {
  2654. //try finding the exit gate
  2655. if(const CGObjectInstance *outGate = getObj(CGTeleport::getMatchingGate(ct->visitableObjects.back()->id), false))
  2656. {
  2657. const int3 outPos = outGate->visitablePos();
  2658. //gs->getNeighbours(*getTile(outPos), outPos, neighbours, boost::logic::indeterminate, !cp->land);
  2659. neighbours.push_back(outPos);
  2660. }
  2661. else
  2662. {
  2663. //gate with no exit (blocked) -> do nothing with this node
  2664. continue;
  2665. }
  2666. }
  2667. gs->getNeighbours(*ct, cp->coord, neighbours, boost::logic::indeterminate, !cp->land);
  2668. for(ui32 i=0; i < neighbours.size(); i++)
  2669. {
  2670. const int3 &n = neighbours[i]; //current neighbor
  2671. dp = getNode(n);
  2672. dt = &gs->map->getTile(n);
  2673. destTopVisObjID = dt->topVisitableID();
  2674. useEmbarkCost = 0; //0 - usual movement; 1 - embark; 2 - disembark
  2675. int turnAtNextTile = turn;
  2676. const bool destIsGuardian = sourceGuardPosition == n;
  2677. if(!goodForLandSeaTransition())
  2678. continue;
  2679. if(!canMoveBetween(cp->coord, dp->coord) || dp->accessible == CGPathNode::BLOCKED )
  2680. continue;
  2681. //special case -> hero embarked a boat standing on a guarded tile -> we must allow to move away from that tile
  2682. if(cp->accessible == CGPathNode::VISITABLE && guardedSource && cp->theNodeBefore->land && ct->topVisitableID() == Obj::BOAT)
  2683. guardedSource = false;
  2684. int cost = gs->getMovementCost(hero, cp->coord, dp->coord, movement);
  2685. //special case -> moving from src Subterranean gate to dest gate -> it's free
  2686. if(subterraneanEntry && destTopVisObjID == Obj::SUBTERRANEAN_GATE && cp->coord.z != dp->coord.z)
  2687. cost = 0;
  2688. int remains = movement - cost;
  2689. if(useEmbarkCost)
  2690. {
  2691. remains = hero->movementPointsAfterEmbark(movement, cost, useEmbarkCost - 1);
  2692. cost = movement - remains;
  2693. }
  2694. if(remains < 0)
  2695. {
  2696. //occurs rarely, when hero with low movepoints tries to leave the road
  2697. turnAtNextTile++;
  2698. int moveAtNextTile = hero->maxMovePoints(cp->land);
  2699. cost = gs->getMovementCost(hero, cp->coord, dp->coord, moveAtNextTile); //cost must be updated, movement points changed :(
  2700. remains = moveAtNextTile - cost;
  2701. }
  2702. if((dp->turns==0xff //we haven't been here before
  2703. || dp->turns > turnAtNextTile
  2704. || (dp->turns >= turnAtNextTile && dp->moveRemains < remains)) //this route is faster
  2705. && (!guardedSource || destIsGuardian)) // Can step into tile of guard
  2706. {
  2707. assert(dp != cp->theNodeBefore); //two tiles can't point to each other
  2708. dp->moveRemains = remains;
  2709. dp->turns = turnAtNextTile;
  2710. dp->theNodeBefore = cp;
  2711. const bool guardedDst = guardingCreaturePosition(dp->coord) != int3(-1, -1, -1)
  2712. && dp->accessible == CGPathNode::BLOCKVIS;
  2713. if (dp->accessible == CGPathNode::ACCESSIBLE
  2714. || (useEmbarkCost && allowEmbarkAndDisembark)
  2715. || destTopVisObjID == Obj::SUBTERRANEAN_GATE
  2716. || (guardedDst && !guardedSource)) // Can step into a hostile tile once.
  2717. {
  2718. mq.push_back(dp);
  2719. }
  2720. }
  2721. } //neighbours loop
  2722. } //queue loop
  2723. out.isValid = true;
  2724. }
  2725. CGPathNode *CPathfinder::getNode(const int3 &coord)
  2726. {
  2727. return &out.nodes[coord.x][coord.y][coord.z];
  2728. }
  2729. bool CPathfinder::canMoveBetween(const int3 &a, const int3 &b) const
  2730. {
  2731. return gs->checkForVisitableDir(a, b) && gs->checkForVisitableDir(b, a);
  2732. }
  2733. bool CPathfinder::canStepOntoDst() const
  2734. {
  2735. //TODO remove
  2736. assert(0);
  2737. return false;
  2738. }
  2739. CGPathNode::EAccessibility CPathfinder::evaluateAccessibility(const TerrainTile *tinfo) const
  2740. {
  2741. CGPathNode::EAccessibility ret = (tinfo->blocked ? CGPathNode::BLOCKED : CGPathNode::ACCESSIBLE);
  2742. if(tinfo->tertype == TerrainTile::rock || !FoW[curPos.x][curPos.y][curPos.z])
  2743. return CGPathNode::BLOCKED;
  2744. if(tinfo->visitable)
  2745. {
  2746. if(tinfo->visitableObjects.front()->ID == 80 && tinfo->visitableObjects.back()->ID == Obj::HERO && tinfo->visitableObjects.back()->tempOwner != hero->tempOwner) //non-owned hero stands on Sanctuary
  2747. {
  2748. return CGPathNode::BLOCKED;
  2749. }
  2750. else
  2751. {
  2752. BOOST_FOREACH(const CGObjectInstance *obj, tinfo->visitableObjects)
  2753. {
  2754. if(obj->getPassableness() & 1<<hero->tempOwner) //special object instance specific passableness flag - overwrites other accessibility flags
  2755. {
  2756. ret = CGPathNode::ACCESSIBLE;
  2757. }
  2758. else if(obj->blockVisit)
  2759. {
  2760. return CGPathNode::BLOCKVIS;
  2761. }
  2762. else if(obj->ID != Obj::EVENT) //pathfinder should ignore placed events
  2763. {
  2764. ret = CGPathNode::VISITABLE;
  2765. }
  2766. }
  2767. }
  2768. }
  2769. else if (gs->map->isInTheMap(guardingCreaturePosition(curPos))
  2770. && !tinfo->blocked)
  2771. {
  2772. // Monster close by; blocked visit for battle.
  2773. return CGPathNode::BLOCKVIS;
  2774. }
  2775. return ret;
  2776. }
  2777. bool CPathfinder::goodForLandSeaTransition()
  2778. {
  2779. if(cp->land != dp->land) //hero can traverse land<->sea only in special circumstances
  2780. {
  2781. if(cp->land) //from land to sea -> embark or assault hero on boat
  2782. {
  2783. if(dp->accessible == CGPathNode::ACCESSIBLE || destTopVisObjID < 0) //cannot enter empty water tile from land -> it has to be visitable
  2784. return false;
  2785. if(destTopVisObjID != Obj::HERO && destTopVisObjID != Obj::BOAT) //only boat or hero can be accessed from land
  2786. return false;
  2787. if(destTopVisObjID == Obj::BOAT)
  2788. useEmbarkCost = 1;
  2789. }
  2790. else //disembark
  2791. {
  2792. //can disembark only on coastal tiles
  2793. if(!dt->isCoastal())
  2794. return false;
  2795. //tile must be accessible -> exception: unblocked blockvis tiles -> clear but guarded by nearby monster coast
  2796. if( (dp->accessible != CGPathNode::ACCESSIBLE && (dp->accessible != CGPathNode::BLOCKVIS || dt->blocked))
  2797. || dt->visitable) //TODO: passableness problem -> town says it's passable (thus accessible) but we obviously can't disembark onto town gate
  2798. return false;;
  2799. useEmbarkCost = 2;
  2800. }
  2801. }
  2802. return true;
  2803. }
  2804. CPathfinder::CPathfinder(CPathsInfo &_out, CGameState *_gs, const CGHeroInstance *_hero) : CGameInfoCallback(_gs, -1), out(_out), hero(_hero), FoW(getPlayerTeam(hero->tempOwner)->fogOfWarMap)
  2805. {
  2806. useSubterraneanGates = true;
  2807. allowEmbarkAndDisembark = true;
  2808. }