CGameState.cpp 83 KB

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