CGameState.cpp 90 KB

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