2
0

CGameState.cpp 96 KB

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