2
0

CGameState.cpp 85 KB

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