CGameState.cpp 94 KB

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