CGameState.cpp 86 KB

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