CGameState.cpp 92 KB

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