CGameState.cpp 85 KB

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