CGameState.cpp 84 KB

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