CGameState.cpp 90 KB

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