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