CGameState.cpp 84 KB

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