CGameState.cpp 98 KB

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