CGameState.cpp 85 KB

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