CGameState.cpp 84 KB

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