CGameState.cpp 91 KB

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