CGameState.cpp 92 KB

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