CGameState.cpp 87 KB

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