CGameState.cpp 86 KB

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