CGameState.cpp 83 KB

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