CGameState.cpp 85 KB

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