CGameState.cpp 86 KB

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