CGameState.cpp 82 KB

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