CGameState.cpp 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060
  1. #define VCMI_DLL
  2. #include <algorithm>
  3. #include <queue>
  4. #include <fstream>
  5. #include "CGameState.h"
  6. #include <boost/random/linear_congruential.hpp>
  7. #include "../hch/CDefObjInfoHandler.h"
  8. #include "../hch/CArtHandler.h"
  9. #include "../hch/CBuildingHandler.h"
  10. #include "../hch/CGeneralTextHandler.h"
  11. #include "../hch/CTownHandler.h"
  12. #include "../hch/CSpellHandler.h"
  13. #include "../hch/CHeroHandler.h"
  14. #include "../hch/CObjectHandler.h"
  15. #include "../hch/CCreatureHandler.h"
  16. #include "VCMI_Lib.h"
  17. #include "Connection.h"
  18. #include "map.h"
  19. #include "../StartInfo.h"
  20. #include "NetPacks.h"
  21. #include <boost/foreach.hpp>
  22. #include <boost/lexical_cast.hpp>
  23. #include <boost/thread.hpp>
  24. #include <boost/thread/shared_mutex.hpp>
  25. #include "RegisterTypes.cpp"
  26. boost::rand48 ran;
  27. #ifdef min
  28. #undef min
  29. #endif
  30. #ifdef max
  31. #undef max
  32. #endif
  33. /*
  34. * CGameState.cpp, part of VCMI engine
  35. *
  36. * Authors: listed in file AUTHORS in main folder
  37. *
  38. * License: GNU General Public License v2.0 or later
  39. * Full text of license available in license.txt file, in main folder
  40. *
  41. */
  42. void foofoofoo()
  43. {
  44. //never called function to force instantation of templates
  45. int *ccc = NULL;
  46. registerTypes((CISer<CConnection>&)*ccc);
  47. registerTypes((COSer<CConnection>&)*ccc);
  48. registerTypes((CSaveFile&)*ccc);
  49. registerTypes((CLoadFile&)*ccc);
  50. registerTypes((CTypeList&)*ccc);
  51. }
  52. class CBaseForGSApply
  53. {
  54. public:
  55. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  56. };
  57. template <typename T> class CApplyOnGS : public CBaseForGSApply
  58. {
  59. public:
  60. void applyOnGS(CGameState *gs, void *pack) const
  61. {
  62. T *ptr = static_cast<T*>(pack);
  63. while(!gs->mx->try_lock())
  64. boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  65. ptr->applyGs(gs);
  66. gs->mx->unlock();
  67. }
  68. };
  69. class CGSApplier
  70. {
  71. public:
  72. std::map<ui16,CBaseForGSApply*> apps;
  73. CGSApplier()
  74. {
  75. registerTypes2(*this);
  76. }
  77. template<typename T> void registerType(const T * t=NULL)
  78. {
  79. ui16 ID = typeList.registerType(t);
  80. apps[ID] = new CApplyOnGS<T>;
  81. }
  82. } *applierGs = NULL;
  83. class IObjectCaller
  84. {
  85. public:
  86. virtual void preInit()=0;
  87. virtual void postInit()=0;
  88. };
  89. template <typename T>
  90. class CObjectCaller : public IObjectCaller
  91. {
  92. public:
  93. void preInit()
  94. {
  95. T::preInit();
  96. }
  97. void postInit()
  98. {
  99. T::postInit();
  100. }
  101. };
  102. class CObjectCallersHandler
  103. {
  104. public:
  105. std::vector<IObjectCaller*> apps;
  106. template<typename T> void registerType(const T * t=NULL)
  107. {
  108. apps.push_back(new CObjectCaller<T>);
  109. }
  110. CObjectCallersHandler()
  111. {
  112. registerTypes1(*this);
  113. }
  114. ~CObjectCallersHandler()
  115. {
  116. for (size_t i = 0; i < apps.size(); i++)
  117. delete apps[i];
  118. }
  119. void preInit()
  120. {
  121. for (size_t i = 0; i < apps.size(); i++)
  122. apps[i]->preInit();
  123. }
  124. void postInit()
  125. {
  126. for (size_t i = 0; i < apps.size(); i++)
  127. apps[i]->postInit();
  128. }
  129. } *objCaller = NULL;
  130. void MetaString::getLocalString(const std::pair<ui8,ui32> &txt, std::string &dst) const
  131. {
  132. int type = txt.first, ser = txt.second;
  133. if(type == ART_NAMES)
  134. {
  135. dst = VLC->arth->artifacts[ser].Name();
  136. }
  137. else if(type == CRE_PL_NAMES)
  138. {
  139. dst = VLC->creh->creatures[ser].namePl;
  140. }
  141. else if(type == MINE_NAMES)
  142. {
  143. dst = VLC->generaltexth->mines[ser].first;
  144. }
  145. else if(type == MINE_EVNTS)
  146. {
  147. dst = VLC->generaltexth->mines[ser].second;
  148. }
  149. else if(type == SPELL_NAME)
  150. {
  151. dst = VLC->spellh->spells[ser].name;
  152. }
  153. else if(type == CRE_SING_NAMES)
  154. {
  155. dst = VLC->creh->creatures[ser].nameSing;
  156. }
  157. else
  158. {
  159. std::vector<std::string> *vec;
  160. switch(type)
  161. {
  162. case GENERAL_TXT:
  163. vec = &VLC->generaltexth->allTexts;
  164. break;
  165. case XTRAINFO_TXT:
  166. vec = &VLC->generaltexth->xtrainfo;
  167. break;
  168. case OBJ_NAMES:
  169. vec = &VLC->generaltexth->names;
  170. break;
  171. case RES_NAMES:
  172. vec = &VLC->generaltexth->restypes;
  173. break;
  174. case ARRAY_TXT:
  175. vec = &VLC->generaltexth->arraytxt;
  176. break;
  177. case CREGENS:
  178. vec = &VLC->generaltexth->creGens;
  179. break;
  180. case CREGENS4:
  181. vec = &VLC->generaltexth->creGens4;
  182. break;
  183. case ADVOB_TXT:
  184. vec = &VLC->generaltexth->advobtxt;
  185. break;
  186. case ART_EVNTS:
  187. vec = &VLC->generaltexth->artifEvents;
  188. break;
  189. case SEC_SKILL_NAME:
  190. vec = &VLC->generaltexth->skillName;
  191. break;
  192. }
  193. dst = (*vec)[ser];
  194. }
  195. }
  196. DLL_EXPORT void MetaString::toString(std::string &dst) const
  197. {
  198. size_t exSt = 0, loSt = 0, nums = 0;
  199. dst.clear();
  200. for(size_t i=0;i<message.size();++i)
  201. {//TEXACT_STRING, TLOCAL_STRING, TNUMBER, TREPLACE_ESTRING, TREPLACE_LSTRING, TREPLACE_NUMBER
  202. switch(message[i])
  203. {
  204. case TEXACT_STRING:
  205. dst += exactStrings[exSt++];
  206. break;
  207. case TLOCAL_STRING:
  208. {
  209. std::string hlp;
  210. getLocalString(localStrings[loSt++], hlp);
  211. dst += hlp;
  212. }
  213. break;
  214. case TNUMBER:
  215. dst += boost::lexical_cast<std::string>(numbers[nums++]);
  216. break;
  217. case TREPLACE_ESTRING:
  218. dst.replace (dst.find("%s"), 2, exactStrings[exSt++]);
  219. break;
  220. case TREPLACE_LSTRING:
  221. {
  222. std::string hlp;
  223. getLocalString(localStrings[loSt++], hlp);
  224. dst.replace (dst.find("%s"), 2, hlp);
  225. }
  226. break;
  227. case TREPLACE_NUMBER:
  228. dst.replace (dst.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  229. break;
  230. default:
  231. tlog1 << "MetaString processing error!\n";
  232. break;
  233. }
  234. }
  235. }
  236. DLL_EXPORT std::string MetaString::buildList () const
  237. ///used to handle loot from creature bank
  238. {
  239. size_t exSt = 0, loSt = 0, nums = 0;
  240. std::string lista;
  241. for (int i = 0; i < message.size(); ++i)
  242. {
  243. if (i > 0 && message[i] == TEXACT_STRING || message[i] == TLOCAL_STRING)
  244. {
  245. if (exSt == exactStrings.size() - 1)
  246. lista += VLC->generaltexth->allTexts[141]; //" and "
  247. else
  248. lista += ", ";
  249. }
  250. switch (message[i])
  251. {
  252. case TEXACT_STRING:
  253. lista += exactStrings[exSt++];
  254. break;
  255. case TLOCAL_STRING:
  256. {
  257. std::string hlp;
  258. getLocalString (localStrings[loSt++], hlp);
  259. lista += hlp;
  260. }
  261. break;
  262. case TNUMBER:
  263. lista += boost::lexical_cast<std::string>(numbers[nums++]);
  264. break;
  265. case TREPLACE_ESTRING:
  266. lista.replace (lista.find("%s"), 2, exactStrings[exSt++]);
  267. break;
  268. case TREPLACE_LSTRING:
  269. {
  270. std::string hlp;
  271. getLocalString (localStrings[loSt++], hlp);
  272. lista.replace (lista.find("%s"), 2, hlp);
  273. }
  274. break;
  275. case TREPLACE_NUMBER:
  276. lista.replace (lista.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  277. break;
  278. default:
  279. tlog1 << "MetaString processing error!\n";
  280. }
  281. }
  282. return lista;
  283. }
  284. static CGObjectInstance * createObject(int id, int subid, int3 pos, int owner)
  285. {
  286. CGObjectInstance * nobj;
  287. switch(id)
  288. {
  289. case HEROI_TYPE: //hero
  290. {
  291. CGHeroInstance * nobj = new CGHeroInstance();
  292. nobj->pos = pos;
  293. nobj->tempOwner = owner;
  294. nobj->subID = subid;
  295. //nobj->initHero(ran);
  296. return nobj;
  297. }
  298. case TOWNI_TYPE: //town
  299. nobj = new CGTownInstance;
  300. break;
  301. default: //rest of objects
  302. nobj = new CGObjectInstance;
  303. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  304. break;
  305. }
  306. nobj->ID = id;
  307. nobj->subID = subid;
  308. if(!nobj->defInfo)
  309. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  310. nobj->pos = pos;
  311. //nobj->state = NULL;//new CLuaObjectScript();
  312. nobj->tempOwner = owner;
  313. nobj->info = NULL;
  314. nobj->defInfo->id = id;
  315. nobj->defInfo->subid = subid;
  316. //assigning defhandler
  317. if(nobj->ID==HEROI_TYPE || nobj->ID==TOWNI_TYPE)
  318. return nobj;
  319. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  320. return nobj;
  321. }
  322. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  323. {
  324. for(unsigned int g=0; g<stacks.size(); ++g)
  325. {
  326. if(stacks[g]->ID == stackID && (!onlyAlive || stacks[g]->alive()))
  327. return stacks[g];
  328. }
  329. return NULL;
  330. }
  331. const CStack * BattleInfo::getStack(int stackID, bool onlyAlive) const
  332. {
  333. return const_cast<BattleInfo * const>(this)->getStack(stackID, onlyAlive);
  334. }
  335. CStack * BattleInfo::getStackT(int tileID, bool onlyAlive)
  336. {
  337. for(unsigned int g=0; g<stacks.size(); ++g)
  338. {
  339. if(stacks[g]->position == tileID
  340. || (stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  341. || (stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  342. {
  343. if(!onlyAlive || stacks[g]->alive())
  344. {
  345. return stacks[g];
  346. }
  347. }
  348. }
  349. return NULL;
  350. }
  351. const CStack * BattleInfo::getStackT(int tileID, bool onlyAlive) const
  352. {
  353. return const_cast<BattleInfo * const>(this)->getStackT(tileID, onlyAlive);
  354. }
  355. void BattleInfo::getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<int> & occupyable, bool flying, int stackToOmmit) const
  356. {
  357. memset(accessibility, 1, BFIELD_SIZE); //initialize array with trues
  358. //removing accessibility for side columns of hexes
  359. for(int v = 0; v < BFIELD_SIZE; ++v)
  360. {
  361. if( v % BFIELD_WIDTH == 0 || v % BFIELD_WIDTH == (BFIELD_WIDTH - 1) )
  362. accessibility[v] = false;
  363. }
  364. for(unsigned int g=0; g<stacks.size(); ++g)
  365. {
  366. if(!stacks[g]->alive() || stacks[g]->ID==stackToOmmit || stacks[g]->position < 0) //we don't want to lock position of this stack (eg. if it's a turret)
  367. continue;
  368. accessibility[stacks[g]->position] = false;
  369. if(stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE)) //if it's a double hex creature
  370. {
  371. if(stacks[g]->attackerOwned)
  372. accessibility[stacks[g]->position-1] = false;
  373. else
  374. accessibility[stacks[g]->position+1] = false;
  375. }
  376. }
  377. //obstacles
  378. for(unsigned int b=0; b<obstacles.size(); ++b)
  379. {
  380. std::vector<int> blocked = VLC->heroh->obstacles[obstacles[b].ID].getBlocked(obstacles[b].pos);
  381. for(unsigned int c=0; c<blocked.size(); ++c)
  382. {
  383. if(blocked[c] >=0 && blocked[c] < BFIELD_SIZE)
  384. accessibility[blocked[c]] = false;
  385. }
  386. }
  387. //walls
  388. if(siege > 0)
  389. {
  390. static const int permanentlyLocked[] = {12, 45, 78, 112, 147, 165};
  391. for(int b=0; b<ARRAY_COUNT(permanentlyLocked); ++b)
  392. {
  393. accessibility[permanentlyLocked[b]] = false;
  394. }
  395. static const std::pair<int, int> lockedIfNotDestroyed[] = //(which part of wall, which hex is blocked if this part of wall is not destroyed
  396. {std::make_pair(2, 182), std::make_pair(3, 130), std::make_pair(4, 62), std::make_pair(5, 29)};
  397. for(int b=0; b<ARRAY_COUNT(lockedIfNotDestroyed); ++b)
  398. {
  399. if(si.wallState[lockedIfNotDestroyed[b].first] < 3)
  400. {
  401. accessibility[lockedIfNotDestroyed[b].second] = false;
  402. }
  403. }
  404. //gate
  405. if(attackerOwned && si.wallState[7] < 3) //if it attacker's unit and gate is not destroyed
  406. {
  407. accessibility[95] = accessibility[96] = false; //block gate's hexes
  408. }
  409. }
  410. //occupyability
  411. if(addOccupiable && twoHex)
  412. {
  413. std::set<int> rem; //tiles to unlock
  414. for(int h=0; h<BFIELD_HEIGHT; ++h)
  415. {
  416. for(int w=1; w<BFIELD_WIDTH-1; ++w)
  417. {
  418. int hex = h * BFIELD_WIDTH + w;
  419. if(!isAccessible(hex, accessibility, twoHex, attackerOwned, flying, true)
  420. && (attackerOwned ? isAccessible(hex+1, accessibility, twoHex, attackerOwned, flying, true) : isAccessible(hex-1, accessibility, twoHex, attackerOwned, flying, true) )
  421. )
  422. rem.insert(hex);
  423. }
  424. }
  425. occupyable = rem;
  426. /*for(std::set<int>::const_iterator it = rem.begin(); it != rem.end(); ++it)
  427. {
  428. accessibility[*it] = true;
  429. }*/
  430. }
  431. }
  432. bool BattleInfo::isAccessible(int hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos)
  433. {
  434. if(flying && !lastPos)
  435. return true;
  436. if(twoHex)
  437. {
  438. //if given hex is accessible and appropriate adjacent one is free too
  439. return accessibility[hex] && accessibility[hex + (attackerOwned ? -1 : 1 )];
  440. }
  441. else
  442. {
  443. return accessibility[hex];
  444. }
  445. }
  446. void BattleInfo::makeBFS(int start, bool *accessibility, int *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying, bool fillPredecessors) const //both pointers must point to the at least 187-elements int arrays
  447. {
  448. //inits
  449. for(int b=0; b<BFIELD_SIZE; ++b)
  450. predecessor[b] = -1;
  451. for(int g=0; g<BFIELD_SIZE; ++g)
  452. dists[g] = 100000000;
  453. std::queue< std::pair<int, bool> > hexq; //bfs queue <hex, accessible> (second filed used only if fillPredecessors is true)
  454. hexq.push(std::make_pair(start, true));
  455. dists[hexq.front().first] = 0;
  456. int curNext = -1; //for bfs loop only (helper var)
  457. while(!hexq.empty()) //bfs loop
  458. {
  459. std::pair<int, bool> curHex = hexq.front();
  460. std::vector<int> neighbours = neighbouringTiles(curHex.first);
  461. hexq.pop();
  462. for(unsigned int nr=0; nr<neighbours.size(); nr++)
  463. {
  464. curNext = neighbours[nr]; //if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  465. bool accessible = isAccessible(curNext, accessibility, twoHex, attackerOwned, flying, dists[curHex.first]+1 == dists[curNext]);
  466. if( dists[curHex.first]+1 >= dists[curNext] )
  467. continue;
  468. if(accessible && curHex.second)
  469. {
  470. hexq.push(std::make_pair(curNext, true));
  471. dists[curNext] = dists[curHex.first] + 1;
  472. }
  473. else if(fillPredecessors && !(accessible && !curHex.second))
  474. {
  475. hexq.push(std::make_pair(curNext, false));
  476. dists[curNext] = dists[curHex.first] + 1;
  477. }
  478. predecessor[curNext] = curHex.first;
  479. }
  480. }
  481. };
  482. std::vector<int> BattleInfo::getAccessibility(int stackID, bool addOccupiable) const
  483. {
  484. std::vector<int> ret;
  485. bool ac[BFIELD_SIZE];
  486. const CStack *s = getStack(stackID);
  487. if(s->position < 0) //turrets
  488. return std::vector<int>();
  489. std::set<int> occupyable;
  490. getAccessibilityMap(ac, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, addOccupiable, occupyable, s->hasFeatureOfType(StackFeature::FLYING), stackID);
  491. int pr[BFIELD_SIZE], dist[BFIELD_SIZE];
  492. makeBFS(s->position, ac, pr, dist, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, s->hasFeatureOfType(StackFeature::FLYING), false);
  493. if(s->hasFeatureOfType(StackFeature::DOUBLE_WIDE))
  494. {
  495. if(!addOccupiable)
  496. {
  497. std::vector<int> rem;
  498. for(int b=0; b<BFIELD_SIZE; ++b)
  499. {
  500. //don't take into account most left and most right columns of hexes
  501. if( b % BFIELD_WIDTH == 0 || b % BFIELD_WIDTH == BFIELD_WIDTH - 1 )
  502. continue;
  503. if( ac[b] && !(s->attackerOwned ? ac[b-1] : ac[b+1]) )
  504. {
  505. rem.push_back(b);
  506. }
  507. }
  508. for(unsigned int g=0; g<rem.size(); ++g)
  509. {
  510. ac[rem[g]] = false;
  511. }
  512. //removing accessibility for side hexes
  513. for(int v=0; v<BFIELD_SIZE; ++v)
  514. if(s->attackerOwned ? (v%BFIELD_WIDTH)==1 : (v%BFIELD_WIDTH)==(BFIELD_WIDTH - 2))
  515. ac[v] = false;
  516. }
  517. }
  518. for (int i=0; i < BFIELD_SIZE ; ++i) {
  519. if(
  520. ( ( !addOccupiable && dist[i] <= s->Speed() && ac[i] ) || ( addOccupiable && dist[i] <= s->Speed() && isAccessible(i, ac, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, s->hasFeatureOfType(StackFeature::FLYING), true) ) )//we can reach it
  521. || (vstd::contains(occupyable, i) && ( dist[ i + (s->attackerOwned ? 1 : -1 ) ] <= s->Speed() ) &&
  522. ac[i + (s->attackerOwned ? 1 : -1 )] ) //it's occupyable and we can reach adjacent hex
  523. )
  524. {
  525. ret.push_back(i);
  526. }
  527. }
  528. return ret;
  529. }
  530. bool BattleInfo::isStackBlocked(int ID)
  531. {
  532. CStack *our = getStack(ID);
  533. if(our->hasFeatureOfType(StackFeature::SIEGE_WEAPON)) //siege weapons cannot be blocked
  534. return false;
  535. for(unsigned int i=0; i<stacks.size();i++)
  536. {
  537. if( !stacks[i]->alive()
  538. || stacks[i]->owner==our->owner
  539. )
  540. continue; //we omit dead and allied stacks
  541. if(stacks[i]->hasFeatureOfType(StackFeature::DOUBLE_WIDE))
  542. {
  543. if( mutualPosition(stacks[i]->position, our->position) >= 0
  544. || mutualPosition(stacks[i]->position + (stacks[i]->attackerOwned ? -1 : 1), our->position) >= 0)
  545. return true;
  546. }
  547. else
  548. {
  549. if( mutualPosition(stacks[i]->position, our->position) >= 0 )
  550. return true;
  551. }
  552. }
  553. return false;
  554. }
  555. signed char BattleInfo::mutualPosition(int hex1, int hex2)
  556. {
  557. if(hex2 == hex1 - ( (hex1/17)%2 ? 18 : 17 )) //top left
  558. return 0;
  559. if(hex2 == hex1 - ( (hex1/17)%2 ? 17 : 16 )) //top right
  560. return 1;
  561. if(hex2 == hex1 - 1 && hex1%17 != 0) //left
  562. return 5;
  563. if(hex2 == hex1 + 1 && hex1%17 != 16) //right
  564. return 2;
  565. if(hex2 == hex1 + ( (hex1/17)%2 ? 16 : 17 )) //bottom left
  566. return 4;
  567. if(hex2 == hex1 + ( (hex1/17)%2 ? 17 : 18 )) //bottom right
  568. return 3;
  569. return -1;
  570. }
  571. std::vector<int> BattleInfo::neighbouringTiles(int hex)
  572. {
  573. #define CHECK_AND_PUSH(tile) {int hlp = (tile); if(hlp>=0 && hlp<BFIELD_SIZE && (hlp%BFIELD_WIDTH!=16) && hlp%BFIELD_WIDTH) ret.push_back(hlp);}
  574. std::vector<int> ret;
  575. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 18 : 17 ));
  576. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 17 : 16 ));
  577. CHECK_AND_PUSH(hex - 1);
  578. CHECK_AND_PUSH(hex + 1);
  579. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 16 : 17 ));
  580. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 17 : 18 ));
  581. #undef CHECK_AND_PUSH
  582. return ret;
  583. }
  584. std::pair< std::vector<int>, int > BattleInfo::getPath(int start, int dest, bool*accessibility, bool flyingCreature, bool twoHex, bool attackerOwned)
  585. {
  586. int predecessor[BFIELD_SIZE]; //for getting the Path
  587. int dist[BFIELD_SIZE]; //calculated distances
  588. makeBFS(start, accessibility, predecessor, dist, twoHex, attackerOwned, flyingCreature, false);
  589. if(predecessor[dest] == -1) //cannot reach destination
  590. {
  591. return std::make_pair(std::vector<int>(), 0);
  592. }
  593. //making the Path
  594. std::vector<int> path;
  595. int curElem = dest;
  596. while(curElem != start)
  597. {
  598. path.push_back(curElem);
  599. curElem = predecessor[curElem];
  600. }
  601. return std::make_pair(path, dist[dest]);
  602. }
  603. int CStack::valOfFeatures(StackFeature::ECombatFeatures type, int subtype, int turn) const
  604. {
  605. int ret = 0;
  606. if(subtype == -1024) //any subtype
  607. {
  608. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  609. if(i->type == type && (!turn || i->turnsRemain > turn))
  610. ret += i->value;
  611. }
  612. else //given subtype
  613. {
  614. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  615. if(i->type == type && i->subtype == subtype && (!turn || i->turnsRemain > turn))
  616. ret += i->value;
  617. }
  618. return ret;
  619. }
  620. bool CStack::hasFeatureOfType(StackFeature::ECombatFeatures type, int subtype, int turn) const
  621. {
  622. if(subtype == -1024) //any subtype
  623. {
  624. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  625. if(i->type == type && (!turn || i->turnsRemain > turn))
  626. return true;
  627. }
  628. else //given subtype
  629. {
  630. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  631. if(i->type == type && i->subtype == subtype && (!turn || i->turnsRemain > turn))
  632. return true;
  633. }
  634. return false;
  635. }
  636. CStack::CStack(CCreature * C, int A, int O, int I, bool AO, int S)
  637. :ID(I), creature(C), amount(A), baseAmount(A), firstHPleft(C->hitPoints), owner(O), slot(S), attackerOwned(AO), position(-1),
  638. counterAttacks(1), shots(C->shots), features(C->abilities)
  639. {
  640. //additional retaliations
  641. for(int h=0; h<C->abilities.size(); ++h)
  642. {
  643. if(C->abilities[h].type == StackFeature::ADDITIONAL_RETALIATION)
  644. {
  645. counterAttacks += C->abilities[h].value;
  646. }
  647. }
  648. //alive state indication
  649. state.insert(ALIVE);
  650. }
  651. ui32 CStack::Speed( int turn /*= 0*/ ) const
  652. {
  653. if(hasFeatureOfType(StackFeature::SIEGE_WEAPON, -1024, turn)) //war machnes cannot move
  654. return 0;
  655. int speed = creature->speed;
  656. speed += valOfFeatures(StackFeature::SPEED_BONUS, -1024, turn);
  657. int percentBonus = 0;
  658. for(int g=0; g<features.size(); ++g)
  659. {
  660. if(features[g].type == StackFeature::SPEED_BONUS, -1024, turn)
  661. {
  662. percentBonus += features[g].additionalInfo;
  663. }
  664. }
  665. if(percentBonus < 0)
  666. {
  667. speed = (abs(percentBonus) * speed)/100;
  668. }
  669. else
  670. {
  671. speed = ((100 + percentBonus) * speed)/100;
  672. }
  673. //bind effect check
  674. if(getEffect(72))
  675. {
  676. return 0;
  677. }
  678. return speed;
  679. }
  680. const CStack::StackEffect * CStack::getEffect( ui16 id, int turn /*= 0*/ ) const
  681. {
  682. for (unsigned int i=0; i< effects.size(); i++)
  683. if(effects[i].id == id)
  684. if(!turn || effects[i].turnsRemain > turn)
  685. return &effects[i];
  686. return NULL;
  687. }
  688. ui8 CStack::howManyEffectsSet(ui16 id) const
  689. {
  690. ui8 ret = 0;
  691. for (unsigned int i=0; i< effects.size(); i++)
  692. if(effects[i].id == id) //effect found
  693. {
  694. ++ret;
  695. }
  696. return ret;
  697. }
  698. si8 CStack::Morale() const
  699. {
  700. si8 ret = morale;
  701. if(hasFeatureOfType(StackFeature::NON_LIVING) || hasFeatureOfType(StackFeature::UNDEAD) || hasFeatureOfType(StackFeature::NO_MORALE))
  702. return 0;
  703. ret += valOfFeatures(StackFeature::MORALE_BONUS); //mirth & sorrow & other
  704. if(hasFeatureOfType(StackFeature::SELF_MORALE)) //eg. minotaur
  705. {
  706. ret = std::max<si8>(ret, +1);
  707. }
  708. if(ret > 3) ret = 3;
  709. if(ret < -3) ret = -3;
  710. return ret;
  711. }
  712. si8 CStack::Luck() const
  713. {
  714. si8 ret = luck;
  715. if(hasFeatureOfType(StackFeature::NO_LUCK))
  716. return 0;
  717. ret += valOfFeatures(StackFeature::LUCK_BONUS); //fortune & misfortune & other
  718. if(hasFeatureOfType(StackFeature::SELF_LUCK)) //eg. halfling
  719. {
  720. ret = std::max<si8>(ret, +1);
  721. }
  722. if(ret > 3) ret = 3;
  723. if(ret < -3) ret = -3;
  724. return ret;
  725. }
  726. si32 CStack::Attack() const
  727. {
  728. si32 ret = creature->attack; //value to be returned
  729. if(hasFeatureOfType(StackFeature::IN_FRENZY)) //frenzy for attacker
  730. {
  731. ret += si32(VLC->spellh->spells[56].powers[getEffect(56)->level]/100.0) * Defense(false);
  732. }
  733. ret += valOfFeatures(StackFeature::ATTACK_BONUS);
  734. return ret;
  735. }
  736. si32 CStack::Defense(bool withFrenzy /*= true*/) const
  737. {
  738. si32 ret = creature->defence;
  739. if(withFrenzy && getEffect(56)) //frenzy for defender
  740. {
  741. return 0;
  742. }
  743. ret += valOfFeatures(StackFeature::DEFENCE_BONUS);
  744. return ret;
  745. }
  746. ui16 CStack::MaxHealth() const
  747. {
  748. return creature->hitPoints + valOfFeatures(StackFeature::HP_BONUS);
  749. }
  750. bool CStack::willMove(int turn /*= 0*/) const
  751. {
  752. return ( turn ? true : !vstd::contains(state, DEFENDING) )
  753. && !moved(turn)
  754. && canMove(turn);
  755. }
  756. bool CStack::canMove( int turn /*= 0*/ ) const
  757. {
  758. return alive()
  759. && !hasFeatureOfType(StackFeature::NOT_ACTIVE, -1024, turn); //eg. Ammo Cart
  760. }
  761. bool CStack::moved( int turn /*= 0*/ ) const
  762. {
  763. if(!turn)
  764. return vstd::contains(state, MOVED);
  765. else
  766. return false;
  767. }
  768. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native, int player, const CTown *town, std::map<ui32,CGHeroInstance *> &available) const
  769. {
  770. CGHeroInstance *ret = NULL;
  771. if(player<0 || player>=PLAYER_LIMIT)
  772. {
  773. tlog1 << "Cannot pick hero for " << town->Name() << ". Wrong owner!\n";
  774. return NULL;
  775. }
  776. std::vector<CGHeroInstance *> pool;
  777. if(native)
  778. {
  779. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  780. {
  781. if(pavailable.find(i->first)->second & 1<<player
  782. && i->second->type->heroType/2 == town->typeID)
  783. {
  784. pool.push_back(i->second);
  785. }
  786. }
  787. if(!pool.size())
  788. {
  789. tlog1 << "Cannot pick native hero for " << player << ". Picking any...\n";
  790. return pickHeroFor(false, player, town, available);
  791. }
  792. else
  793. {
  794. ret = pool[rand()%pool.size()];
  795. }
  796. }
  797. else
  798. {
  799. int sum=0, r;
  800. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  801. {
  802. if(pavailable.find(i->first)->second & 1<<player)
  803. {
  804. pool.push_back(i->second);
  805. sum += i->second->type->heroClass->selectionProbability[town->typeID];
  806. }
  807. }
  808. if(!pool.size())
  809. {
  810. tlog1 << "There are no heroes available for player " << player<<"!\n";
  811. return NULL;
  812. }
  813. r = rand()%sum;
  814. for(unsigned int i=0; i<pool.size(); i++)
  815. {
  816. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  817. if(r<0)
  818. ret = pool[i];
  819. }
  820. if(!ret)
  821. ret = pool.back();
  822. }
  823. available.erase(ret->subID);
  824. return ret;
  825. }
  826. //void CGameState::apply(CPack * pack)
  827. //{
  828. // while(!mx->try_lock())
  829. // boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  830. // //applyNL(pack);
  831. // mx->unlock();
  832. //}
  833. int CGameState::pickHero(int owner)
  834. {
  835. int h=-1;
  836. if(!map->getHero(h = scenarioOps->getIthPlayersSettings(owner).hero,0) && h>=0) //we haven't used selected hero
  837. return h;
  838. int f = scenarioOps->getIthPlayersSettings(owner).castle;
  839. int i=0;
  840. do //try to find free hero of our faction
  841. {
  842. i++;
  843. h = scenarioOps->getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  844. } while( map->getHero(h) && i<175);
  845. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  846. {
  847. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  848. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  849. if(!map->getHero(j))
  850. h=j;
  851. }
  852. return h;
  853. }
  854. CGHeroInstance *CGameState::getHero(int objid)
  855. {
  856. if(objid<0 || objid>=map->objects.size() || map->objects[objid]->ID!=HEROI_TYPE)
  857. return NULL;
  858. return static_cast<CGHeroInstance *>(map->objects[objid]);
  859. }
  860. CGTownInstance *CGameState::getTown(int objid)
  861. {
  862. if(objid<0 || objid>=map->objects.size())
  863. return NULL;
  864. return static_cast<CGTownInstance *>(map->objects[objid]);
  865. }
  866. std::pair<int,int> CGameState::pickObject(CGObjectInstance *obj)
  867. {
  868. switch(obj->ID)
  869. {
  870. case 65: //random artifact
  871. return std::pair<int,int>(5,(ran()%136)+7); //tylko sensowny zakres - na poczatku sa katapulty itp, na koncu specjalne i blanki
  872. case 66: //random treasure artifact
  873. return std::pair<int,int>(5,VLC->arth->treasures[ran()%VLC->arth->treasures.size()]->id);
  874. case 67: //random minor artifact
  875. return std::pair<int,int>(5,VLC->arth->minors[ran()%VLC->arth->minors.size()]->id);
  876. case 68: //random major artifact
  877. return std::pair<int,int>(5,VLC->arth->majors[ran()%VLC->arth->majors.size()]->id);
  878. case 69: //random relic artifact
  879. return std::pair<int,int>(5,VLC->arth->relics[ran()%VLC->arth->relics.size()]->id);
  880. case 70: //random hero
  881. {
  882. return std::pair<int,int>(HEROI_TYPE,pickHero(obj->tempOwner));
  883. }
  884. case 71: //random monster
  885. {
  886. int r;
  887. do
  888. {
  889. r = ran()%197;
  890. } while (vstd::contains(VLC->creh->notUsedMonsters,r));
  891. return std::pair<int,int>(54,r);
  892. }
  893. case 72: //random monster lvl1
  894. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  895. case 73: //random monster lvl2
  896. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  897. case 74: //random monster lvl3
  898. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  899. case 75: //random monster lvl4
  900. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  901. case 76: //random resource
  902. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  903. case 77: //random town
  904. {
  905. int align = (static_cast<CGTownInstance*>(obj))->alignment,
  906. f;
  907. if(align>PLAYER_LIMIT-1)//same as owner / random
  908. {
  909. if(obj->tempOwner > PLAYER_LIMIT-1)
  910. f = -1; //random
  911. else
  912. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  913. }
  914. else
  915. {
  916. f = scenarioOps->getIthPlayersSettings(align).castle;
  917. }
  918. if(f<0) f = ran()%VLC->townh->towns.size();
  919. return std::pair<int,int>(TOWNI_TYPE,f);
  920. }
  921. case 162: //random monster lvl5
  922. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  923. case 163: //random monster lvl6
  924. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  925. case 164: //random monster lvl7
  926. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  927. case 216: //random dwelling
  928. {
  929. int faction = ran()%F_NUMBER;
  930. CCreGen2ObjInfo* info = static_cast<CCreGen2ObjInfo*>(obj->info);
  931. if (info->asCastle)
  932. {
  933. for(unsigned int i=0;i<map->objects.size();i++)
  934. {
  935. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  936. {
  937. randomizeObject(map->objects[i]); //we have to randomize the castle first
  938. faction = map->objects[i]->subID;
  939. break;
  940. }
  941. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  942. {
  943. faction = map->objects[i]->subID;
  944. break;
  945. }
  946. }
  947. }
  948. else
  949. {
  950. while((!(info->castles[0]&(1<<faction))))
  951. {
  952. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  953. break;
  954. faction = ran()%F_NUMBER;
  955. }
  956. }
  957. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  958. int cid = VLC->townh->towns[faction].basicCreatures[level];
  959. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  960. if(VLC->objh->cregens[i]==cid)
  961. return std::pair<int,int>(17,i);
  962. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  963. return std::pair<int,int>(17,0);
  964. }
  965. case 217:
  966. {
  967. int faction = ran()%F_NUMBER;
  968. CCreGenObjInfo* info = static_cast<CCreGenObjInfo*>(obj->info);
  969. if (info->asCastle)
  970. {
  971. for(unsigned int i=0;i<map->objects.size();i++)
  972. {
  973. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  974. {
  975. randomizeObject(map->objects[i]); //we have to randomize the castle first
  976. faction = map->objects[i]->subID;
  977. break;
  978. }
  979. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  980. {
  981. faction = map->objects[i]->subID;
  982. break;
  983. }
  984. }
  985. }
  986. else
  987. {
  988. while((!(info->castles[0]&(1<<faction))))
  989. {
  990. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  991. break;
  992. faction = ran()%F_NUMBER;
  993. }
  994. }
  995. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  996. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  997. if(VLC->objh->cregens[i]==cid)
  998. return std::pair<int,int>(17,i);
  999. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  1000. return std::pair<int,int>(17,0);
  1001. }
  1002. case 218:
  1003. {
  1004. CCreGen3ObjInfo* info = static_cast<CCreGen3ObjInfo*>(obj->info);
  1005. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  1006. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  1007. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  1008. if(VLC->objh->cregens[i]==cid)
  1009. return std::pair<int,int>(17,i);
  1010. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  1011. return std::pair<int,int>(17,0);
  1012. }
  1013. }
  1014. return std::pair<int,int>(-1,-1);
  1015. }
  1016. void CGameState::randomizeObject(CGObjectInstance *cur)
  1017. {
  1018. std::pair<int,int> ran = pickObject(cur);
  1019. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  1020. {
  1021. if(cur->ID==TOWNI_TYPE) //town - set def
  1022. {
  1023. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  1024. if(t->hasCapitol())
  1025. t->defInfo = capitols[t->subID];
  1026. else if(t->hasFort())
  1027. t->defInfo = forts[t->subID];
  1028. else
  1029. t->defInfo = villages[t->subID];
  1030. }
  1031. return;
  1032. }
  1033. else if(ran.first==HEROI_TYPE)//special code for hero
  1034. {
  1035. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  1036. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  1037. cur->ID = ran.first;
  1038. h->portrait = cur->subID = ran.second;
  1039. h->type = VLC->heroh->heroes[ran.second];
  1040. map->heroes.push_back(h);
  1041. return; //TODO: maybe we should do something with definfo?
  1042. }
  1043. else if(ran.first==TOWNI_TYPE)//special code for town
  1044. {
  1045. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  1046. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  1047. cur->ID = ran.first;
  1048. cur->subID = ran.second;
  1049. t->town = &VLC->townh->towns[ran.second];
  1050. if(t->hasCapitol())
  1051. t->defInfo = capitols[t->subID];
  1052. else if(t->hasFort())
  1053. t->defInfo = forts[t->subID];
  1054. else
  1055. t->defInfo = villages[t->subID];
  1056. map->towns.push_back(t);
  1057. return;
  1058. }
  1059. //we have to replace normal random object
  1060. cur->ID = ran.first;
  1061. cur->subID = ran.second;
  1062. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  1063. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  1064. if(!cur->defInfo)
  1065. {
  1066. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  1067. return;
  1068. }
  1069. map->addBlockVisTiles(cur);
  1070. }
  1071. int CGameState::getDate(int mode) const
  1072. {
  1073. int temp;
  1074. switch (mode)
  1075. {
  1076. case 0:
  1077. return day;
  1078. break;
  1079. case 1:
  1080. temp = (day)%7;
  1081. if (temp)
  1082. return temp;
  1083. else return 7;
  1084. break;
  1085. case 2:
  1086. temp = ((day-1)/7)+1;
  1087. if (!(temp%4))
  1088. return 4;
  1089. else
  1090. return (temp%4);
  1091. break;
  1092. case 3:
  1093. return ((day-1)/28)+1;
  1094. break;
  1095. }
  1096. return 0;
  1097. }
  1098. CGameState::CGameState()
  1099. {
  1100. mx = new boost::shared_mutex();
  1101. map = NULL;
  1102. curB = NULL;
  1103. scenarioOps = NULL;
  1104. applierGs = new CGSApplier;
  1105. objCaller = new CObjectCallersHandler;
  1106. }
  1107. CGameState::~CGameState()
  1108. {
  1109. delete mx;
  1110. delete map;
  1111. delete curB;
  1112. delete scenarioOps;
  1113. delete applierGs;
  1114. delete objCaller;
  1115. }
  1116. void CGameState::init(StartInfo * si, Mapa * map, int Seed)
  1117. {
  1118. day = 0;
  1119. seed = Seed;
  1120. ran.seed((boost::int32_t)seed);
  1121. scenarioOps = si;
  1122. this->map = map;
  1123. loadTownDInfos();
  1124. //picking random factions for players
  1125. for(unsigned int i=0;i<scenarioOps->playerInfos.size();i++)
  1126. {
  1127. if(scenarioOps->playerInfos[i].castle==-1)
  1128. {
  1129. int f;
  1130. do
  1131. {
  1132. f = ran()%F_NUMBER;
  1133. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  1134. scenarioOps->playerInfos[i].castle = f;
  1135. }
  1136. }
  1137. //randomizing objects
  1138. for(unsigned int no=0; no<map->objects.size(); ++no)
  1139. {
  1140. randomizeObject(map->objects[no]);
  1141. if(map->objects[no]->ID==26)
  1142. {
  1143. map->objects[no]->defInfo->handler=NULL;
  1144. }
  1145. map->objects[no]->hoverName = VLC->generaltexth->names[map->objects[no]->ID];
  1146. }
  1147. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  1148. /*********give starting hero****************************************/
  1149. for(int i=0;i<PLAYER_LIMIT;i++)
  1150. {
  1151. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==CMapHeader::RoE))
  1152. {
  1153. int3 hpos = map->players[i].posOfMainTown;
  1154. hpos.x+=1;// hpos.y+=1;
  1155. int j;
  1156. for(j=0; j<scenarioOps->playerInfos.size(); j++) //don't add unsigned here - we are refering to the variable above
  1157. if(scenarioOps->playerInfos[j].color == i)
  1158. break;
  1159. if(j == scenarioOps->playerInfos.size())
  1160. continue;
  1161. int h=pickHero(i);
  1162. if(scenarioOps->playerInfos[j].hero == -1)
  1163. scenarioOps->playerInfos[j].hero = h;
  1164. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(HEROI_TYPE,h,hpos,i));
  1165. nnn->id = map->objects.size();
  1166. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  1167. for(unsigned int o=0;o<map->towns.size();o++) //find main town
  1168. {
  1169. if(map->towns[o]->pos == hpos)
  1170. {
  1171. map->towns[o]->visitingHero = nnn;
  1172. nnn->visitedTown = map->towns[o];
  1173. nnn->inTownGarrison = false;
  1174. break;
  1175. }
  1176. }
  1177. nnn->initHero();
  1178. map->heroes.push_back(nnn);
  1179. map->objects.push_back(nnn);
  1180. map->addBlockVisTiles(nnn);
  1181. }
  1182. }
  1183. /*********creating players entries in gs****************************************/
  1184. for (unsigned int i=0; i<scenarioOps->playerInfos.size();i++)
  1185. {
  1186. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  1187. ins.second.color=ins.first;
  1188. ins.second.serial=i;
  1189. ins.second.human = scenarioOps->playerInfos[i].human;
  1190. players.insert(ins);
  1191. }
  1192. /******************RESOURCES****************************************************/
  1193. //TODO: computer player should receive other amount of resource than computer (depending on difficulty)
  1194. std::vector<int> startres;
  1195. std::ifstream tis("config/startres.txt");
  1196. int k;
  1197. for (int j=0;j<scenarioOps->difficulty;j++)
  1198. {
  1199. tis >> k;
  1200. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1201. tis>>k;
  1202. }
  1203. tis >> k;
  1204. for (int i=0;i<RESOURCE_QUANTITY;i++)
  1205. {
  1206. tis >> k;
  1207. startres.push_back(k);
  1208. }
  1209. tis.close();
  1210. tis.clear();
  1211. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1212. {
  1213. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1214. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1215. (*i).second.resources[x] = startres[x];
  1216. }
  1217. tis.open("config/resources.txt");
  1218. tis >> k;
  1219. int pom;
  1220. for(int i=0;i<k;i++)
  1221. {
  1222. tis >> pom;
  1223. resVals.push_back(pom);
  1224. }
  1225. /*************************HEROES************************************************/
  1226. std::set<int> hids;
  1227. for(unsigned int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1228. if(map->allowedHeroes[i])
  1229. hids.insert(i);
  1230. for (unsigned int i=0; i<map->heroes.size();i++) //heroes instances initialization
  1231. {
  1232. if (map->heroes[i]->getOwner()<0)
  1233. {
  1234. tlog2 << "Warning - hero with uninitialized owner!\n";
  1235. continue;
  1236. }
  1237. CGHeroInstance * vhi = (map->heroes[i]);
  1238. vhi->initHero();
  1239. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1240. hids.erase(vhi->subID);
  1241. }
  1242. for(unsigned int i=0; i<map->predefinedHeroes.size(); i++)
  1243. {
  1244. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1245. continue;
  1246. map->predefinedHeroes[i]->initHero();
  1247. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1248. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1249. hids.erase(map->predefinedHeroes[i]->subID);
  1250. }
  1251. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go into the pool
  1252. {
  1253. CGHeroInstance * vhi = new CGHeroInstance();
  1254. vhi->initHero(hid);
  1255. hpool.heroesPool[hid] = vhi;
  1256. hpool.pavailable[hid] = 0xff;
  1257. }
  1258. for(unsigned int i=0; i<map->disposedHeroes.size(); i++)
  1259. {
  1260. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1261. }
  1262. /*************************FOG**OF**WAR******************************************/
  1263. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1264. {
  1265. k->second.fogOfWarMap.resize(map->width);
  1266. for(int g=0; g<map->width; ++g)
  1267. k->second.fogOfWarMap[g].resize(map->height);
  1268. for(int g=-0; g<map->width; ++g)
  1269. for(int h=0; h<map->height; ++h)
  1270. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1271. for(int g=0; g<map->width; ++g)
  1272. for(int h=0; h<map->height; ++h)
  1273. for(int v=0; v<map->twoLevel+1; ++v)
  1274. k->second.fogOfWarMap[g][h][v] = 0;
  1275. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1276. {
  1277. if(obj->tempOwner != k->first) continue; //not a flagged object
  1278. int3 objCenter = obj->getSightCenter();
  1279. int radious = obj->getSightRadious();
  1280. for (int xd = std::max<int>(objCenter.x - radious , 0); xd <= std::min<int>(objCenter.x + radious, map->width - 1); xd++)
  1281. {
  1282. for (int yd = std::max<int>(objCenter.y - radious, 0); yd <= std::min<int>(objCenter.y + radious, map->height - 1); yd++)
  1283. {
  1284. double distance = objCenter.dist2d(int3(xd,yd,objCenter.z)) - 0.5;
  1285. if(distance <= radious)
  1286. k->second.fogOfWarMap[xd][yd][objCenter.z] = 1;
  1287. }
  1288. }
  1289. }
  1290. //for(int xd=0; xd<map->width; ++xd) //revealing part of map around heroes
  1291. //{
  1292. // for(int yd=0; yd<map->height; ++yd)
  1293. // {
  1294. // for(int ch=0; ch<k->second.heroes.size(); ++ch)
  1295. // {
  1296. // int deltaX = (k->second.heroes[ch]->getPosition(false).x-xd)*(k->second.heroes[ch]->getPosition(false).x-xd);
  1297. // int deltaY = (k->second.heroes[ch]->getPosition(false).y-yd)*(k->second.heroes[ch]->getPosition(false).y-yd);
  1298. // if(deltaX+deltaY<k->second.heroes[ch]->getSightDistance()*k->second.heroes[ch]->getSightDistance())
  1299. // k->second.fogOfWarMap[xd][yd][k->second.heroes[ch]->getPosition(false).z] = 1;
  1300. // }
  1301. // }
  1302. //}
  1303. //starting bonus
  1304. if(si->playerInfos[k->second.serial].bonus==brandom)
  1305. si->playerInfos[k->second.serial].bonus = ran()%3;
  1306. switch(si->playerInfos[k->second.serial].bonus)
  1307. {
  1308. case bgold:
  1309. k->second.resources[6] += 500 + (ran()%6)*100;
  1310. break;
  1311. case bresource:
  1312. {
  1313. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1314. if(res == 127)
  1315. {
  1316. k->second.resources[0] += 5 + ran()%6;
  1317. k->second.resources[2] += 5 + ran()%6;
  1318. }
  1319. else
  1320. {
  1321. k->second.resources[res] += 3 + ran()%4;
  1322. }
  1323. break;
  1324. }
  1325. case bartifact:
  1326. {
  1327. if(!k->second.heroes.size())
  1328. {
  1329. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1330. break;
  1331. }
  1332. CArtifact *toGive;
  1333. do
  1334. {
  1335. toGive = VLC->arth->treasures[ran() % VLC->arth->treasures.size()];
  1336. } while (!map->allowedArtifact[toGive->id]);
  1337. CGHeroInstance *hero = k->second.heroes[0];
  1338. std::vector<ui16>::iterator slot = vstd::findFirstNot(hero->artifWorn,toGive->possibleSlots);
  1339. if(slot!=toGive->possibleSlots.end())
  1340. {
  1341. hero->artifWorn[*slot] = toGive->id;
  1342. hero->recreateArtBonuses();
  1343. }
  1344. else
  1345. hero->artifacts.push_back(toGive->id);
  1346. }
  1347. }
  1348. }
  1349. /****************************TOWNS************************************************/
  1350. for (unsigned int i=0;i<map->towns.size();i++)
  1351. {
  1352. CGTownInstance * vti =(map->towns[i]);
  1353. if(!vti->town)
  1354. vti->town = &VLC->townh->towns[vti->subID];
  1355. if (vti->name.length()==0) // if town hasn't name we draw it
  1356. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1357. //init buildings
  1358. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1359. {
  1360. vti->builtBuildings.erase(-50);
  1361. vti->builtBuildings.insert(10);
  1362. vti->builtBuildings.insert(5);
  1363. vti->builtBuildings.insert(30);
  1364. if(ran()%2)
  1365. vti->builtBuildings.insert(31);
  1366. }
  1367. //init spells
  1368. vti->spells.resize(SPELL_LEVELS);
  1369. CSpell *s;
  1370. for(unsigned int z=0; z<vti->obligatorySpells.size();z++)
  1371. {
  1372. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1373. vti->spells[s->level-1].push_back(s->id);
  1374. vti->possibleSpells -= s->id;
  1375. }
  1376. while(vti->possibleSpells.size())
  1377. {
  1378. ui32 total=0, sel=-1;
  1379. for(unsigned int ps=0;ps<vti->possibleSpells.size();ps++)
  1380. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1381. int r = (total)? ran()%total : -1;
  1382. for(unsigned int ps=0; ps<vti->possibleSpells.size();ps++)
  1383. {
  1384. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1385. if(r<0)
  1386. {
  1387. sel = ps;
  1388. break;
  1389. }
  1390. }
  1391. if(sel<0)
  1392. sel=0;
  1393. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1394. vti->spells[s->level-1].push_back(s->id);
  1395. vti->possibleSpells -= s->id;
  1396. }
  1397. //init garrisons
  1398. for (std::map<si32,std::pair<ui32,si32> >::iterator j=vti->army.slots.begin(); j!=vti->army.slots.end();j++)
  1399. {
  1400. if(j->second.first > 196 && j->second.first < 211)
  1401. {
  1402. if(j->second.first%2)
  1403. j->second.first = vti->town->basicCreatures[ (j->second.first-197) / 2 ];
  1404. else
  1405. j->second.first = vti->town->upgradedCreatures[ (j->second.first-197) / 2 ];
  1406. }
  1407. }
  1408. if(vti->getOwner() != 255)
  1409. getPlayer(vti->getOwner())->towns.push_back(vti);
  1410. }
  1411. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1412. {
  1413. if(k->first==-1 || k->first==255)
  1414. continue;
  1415. //init visiting and garrisoned heroes
  1416. for(unsigned int l=0; l<k->second.heroes.size();l++)
  1417. {
  1418. CGHeroInstance *h = k->second.heroes[l];
  1419. for(unsigned int m=0; m<k->second.towns.size();m++)
  1420. {
  1421. CGTownInstance *t = k->second.towns[m];
  1422. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1423. if(vistile == h->pos || h->pos==t->pos)
  1424. {
  1425. t->visitingHero = h;
  1426. h->visitedTown = t;
  1427. h->inTownGarrison = false;
  1428. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1429. {
  1430. map->removeBlockVisTiles(h);
  1431. h->pos.x -= 1;
  1432. map->addBlockVisTiles(h);
  1433. }
  1434. break;
  1435. }
  1436. }
  1437. }
  1438. }
  1439. for(unsigned int i=0; i<map->defy.size(); i++)
  1440. {
  1441. map->defy[i]->serial = i;
  1442. }
  1443. objCaller->preInit();
  1444. for(unsigned int i=0; i<map->objects.size(); i++)
  1445. {
  1446. map->objects[i]->initObj();
  1447. if(map->objects[i]->ID == 62) //prison also needs to initialize hero
  1448. static_cast<CGHeroInstance*>(map->objects[i])->initHero();
  1449. }
  1450. objCaller->postInit();
  1451. }
  1452. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1453. {
  1454. return true;
  1455. }
  1456. bool CGameState::battleCanFlee(int player)
  1457. {
  1458. if(!curB) //there is no battle
  1459. return false;
  1460. const CGHeroInstance *h1 = getHero(curB->hero1);
  1461. const CGHeroInstance *h2 = getHero(curB->hero2);
  1462. if(h1 && h1->hasBonusOfType(HeroBonus::ENEMY_CANT_ESCAPE) //eg. one of heroes is wearing shakles of war
  1463. || h2 && h2->hasBonusOfType(HeroBonus::ENEMY_CANT_ESCAPE))
  1464. return false;
  1465. return true;
  1466. }
  1467. int CGameState::battleGetStack(int pos, bool onlyAlive)
  1468. {
  1469. if(!curB)
  1470. return -1;
  1471. for(unsigned int g=0; g<curB->stacks.size(); ++g)
  1472. {
  1473. if((curB->stacks[g]->position == pos
  1474. || (curB->stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE)
  1475. &&( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos)
  1476. || (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos) )
  1477. ))
  1478. && (!onlyAlive || curB->stacks[g]->alive())
  1479. )
  1480. return curB->stacks[g]->ID;
  1481. }
  1482. return -1;
  1483. }
  1484. int CGameState::battleGetBattlefieldType(int3 tile)
  1485. {
  1486. if(tile==int3() && curB)
  1487. tile = curB->tile;
  1488. else if(tile==int3() && !curB)
  1489. return -1;
  1490. const std::vector <CGObjectInstance*> & objs = map->objects;
  1491. for(int g=0; g<objs.size(); ++g)
  1492. {
  1493. if( !objs[g] || objs[g]->pos.x - tile.x < 0 || objs[g]->pos.x - tile.x >= 8
  1494. || tile.y - objs[g]->pos.y + 5 < 0 || tile.y - objs[g]->pos.y + 5 >=6
  1495. || !objs[g]->coveringAt(objs[g]->pos.x - tile.x, tile.y - objs[g]->pos.y + 5)
  1496. ) //look only for objects covering given tile
  1497. continue;
  1498. switch(objs[g]->ID)
  1499. {
  1500. case 222: //clover field
  1501. return 19;
  1502. case 21: case 223: //cursed ground
  1503. return 22;
  1504. case 224: //evil fog
  1505. return 20;
  1506. case 225: //favourable winds
  1507. return 21;
  1508. case 226: //fiery fields
  1509. return 14;
  1510. case 227: //holy ground
  1511. return 18;
  1512. case 228: //lucid pools
  1513. return 17;
  1514. case 229: //magic clouds
  1515. return 16;
  1516. case 46: case 230: //magic plains
  1517. return 9;
  1518. case 231: //rocklands
  1519. return 15;
  1520. }
  1521. }
  1522. switch(map->terrain[tile.x][tile.y][tile.z].tertype)
  1523. {
  1524. case TerrainTile::dirt:
  1525. return rand()%3+3;
  1526. case TerrainTile::sand:
  1527. return 2; //TODO: coast support
  1528. case TerrainTile::grass:
  1529. return rand()%2+6;
  1530. case TerrainTile::snow:
  1531. return rand()%2+10;
  1532. case TerrainTile::swamp:
  1533. return 13;
  1534. case TerrainTile::rough:
  1535. return 23;
  1536. case TerrainTile::subterranean:
  1537. return 12;
  1538. case TerrainTile::lava:
  1539. return 8;
  1540. case TerrainTile::water:
  1541. return 25;
  1542. case TerrainTile::rock:
  1543. return 15;
  1544. default:
  1545. return -1;
  1546. }
  1547. }
  1548. const CGHeroInstance * CGameState::battleGetOwner(int stackID)
  1549. {
  1550. if(!curB)
  1551. return NULL;
  1552. si32 ourHero = curB->getStack(stackID)->attackerOwned ? curB->hero1 : curB->hero2;
  1553. return getHero(ourHero);
  1554. }
  1555. UpgradeInfo CGameState::getUpgradeInfo(const CArmedInstance *obj, int stackPos)
  1556. {
  1557. UpgradeInfo ret;
  1558. const CCreature *base = &VLC->creh->creatures[obj->army.slots.find(stackPos)->first];
  1559. if((obj->ID == TOWNI_TYPE) || ((obj->ID == HEROI_TYPE) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
  1560. {
  1561. const CGTownInstance * t;
  1562. if(obj->ID == TOWNI_TYPE)
  1563. t = static_cast<const CGTownInstance *>(obj);
  1564. else
  1565. t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
  1566. for(std::set<si32>::const_iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++)
  1567. {
  1568. if( (*i) >= 37 && (*i) < 44 ) //upgraded creature dwelling
  1569. {
  1570. int nid = t->town->upgradedCreatures[(*i)-37]; //upgrade offered by that building
  1571. if(base->upgrades.find(nid) != base->upgrades.end()) //possible upgrade
  1572. {
  1573. ret.newID.push_back(nid);
  1574. ret.cost.push_back(std::set<std::pair<int,int> >());
  1575. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1576. {
  1577. int dif = VLC->creh->creatures[nid].cost[j] - base->cost[j];
  1578. if(dif)
  1579. ret.cost[ret.cost.size()-1].insert(std::make_pair(j,dif));
  1580. }
  1581. }
  1582. }
  1583. }//end for
  1584. }
  1585. //TODO: check if hero ability makes some upgrades possible
  1586. if(ret.newID.size())
  1587. ret.oldID = base->idNumber;
  1588. return ret;
  1589. }
  1590. float CGameState::getMarketEfficiency( int player, int mode/*=0*/ )
  1591. {
  1592. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1593. if(mode) return -1; //todo - support other modes
  1594. int mcount = 0;
  1595. for(unsigned int i=0;i<getPlayer(player)->towns.size();i++)
  1596. if(vstd::contains(getPlayer(player)->towns[i]->builtBuildings,14))
  1597. mcount++;
  1598. float ret = std::min(((float)mcount+1.0f)/20.0f,0.5f);
  1599. return ret;
  1600. }
  1601. void CGameState::loadTownDInfos()
  1602. {
  1603. for(int i=0;i<F_NUMBER;i++)
  1604. {
  1605. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1606. forts[i] = VLC->dobjinfo->castles[i];
  1607. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1608. }
  1609. }
  1610. void CGameState::getNeighbours( const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand )
  1611. {
  1612. static int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1613. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1614. vec.clear();
  1615. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1616. {
  1617. const int3 hlp = tile + dirs[i];
  1618. if(!map->isInTheMap(hlp))
  1619. continue;
  1620. const TerrainTile &hlpt = map->getTile(hlp);
  1621. if((indeterminate(onLand) || onLand == (hlpt.tertype!=8) )
  1622. && hlpt.tertype!=9)
  1623. {
  1624. vec.push_back(hlp);
  1625. }
  1626. }
  1627. }
  1628. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  1629. {
  1630. if(src == dest) //same tile
  1631. return 0;
  1632. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1633. &d = map->terrain[dest.x][dest.y][dest.z];
  1634. //get basic cost
  1635. int ret = h->getTileCost(d,s);
  1636. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1637. {
  1638. int old = ret;
  1639. ret *= 1.414213;
  1640. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1641. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1642. {
  1643. return remainingMovePoints;
  1644. }
  1645. }
  1646. int left = remainingMovePoints-ret;
  1647. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1648. {
  1649. std::vector<int3> vec;
  1650. getNeighbours(d, dest, vec, s.tertype != TerrainTile::water);
  1651. for(size_t i=0; i < vec.size(); i++)
  1652. {
  1653. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1654. if(fcost <= left)
  1655. {
  1656. return ret;
  1657. }
  1658. }
  1659. ret = remainingMovePoints;
  1660. }
  1661. return ret;
  1662. }
  1663. int CGameState::canBuildStructure( const CGTownInstance *t, int ID )
  1664. {
  1665. int ret = 7; //allowed by default
  1666. //checking resources
  1667. CBuilding * pom = VLC->buildh->buildings[t->subID][ID];
  1668. if(!pom)return 8;
  1669. if(pom->Name().size()==0||pom->resources.size()==0)return 2;//TODO: why does this happen?
  1670. for(int res=0;res<pom->resources.size();res++) //TODO: support custom amount of resources
  1671. {
  1672. if(pom->resources[res] > getPlayer(t->tempOwner)->resources[res])
  1673. ret = 6; //lack of res
  1674. }
  1675. //checking for requirements
  1676. for( std::set<int>::iterator ri = VLC->townh->requirements[t->subID][ID].begin();
  1677. ri != VLC->townh->requirements[t->subID][ID].end();
  1678. ri++ )
  1679. {
  1680. if(t->builtBuildings.find(*ri)==t->builtBuildings.end())
  1681. ret = 8; //lack of requirements - cannot build
  1682. }
  1683. //can we build it?
  1684. if(t->forbiddenBuildings.find(ID)!=t->forbiddenBuildings.end())
  1685. ret = 2; //forbidden
  1686. else if(t->builded >= MAX_BUILDING_PER_TURN)
  1687. ret = 5; //building limit
  1688. if(ID == 13) //capitol
  1689. {
  1690. for(unsigned int in = 0; in < map->towns.size(); in++)
  1691. {
  1692. if(map->towns[in]->tempOwner==t->tempOwner && vstd::contains(map->towns[in]->builtBuildings,13))
  1693. {
  1694. ret = 0; //no more than one capitol
  1695. break;
  1696. }
  1697. }
  1698. }
  1699. else if(ID == 6) //shipyard
  1700. {
  1701. int3 t1(t->pos + int3(-1,3,0)),
  1702. t2(t->pos + int3(-3,3,0));
  1703. if(map->isInTheMap(t1) && map->getTile(t1).tertype != TerrainTile::water
  1704. && (map->isInTheMap(t2) && map->getTile(t2).tertype != TerrainTile::water))
  1705. ret = 1; //lack of water
  1706. }
  1707. if(t->builtBuildings.find(ID)!=t->builtBuildings.end()) //already built
  1708. ret = 4;
  1709. return ret;
  1710. }
  1711. void CGameState::apply(CPack *pack)
  1712. {
  1713. ui16 typ = typeList.getTypeID(pack);
  1714. assert(typ >= 0);
  1715. applierGs->apps[typ]->applyOnGS(this,pack);
  1716. }
  1717. PlayerState * CGameState::getPlayer( ui8 color )
  1718. {
  1719. if(vstd::contains(players,color))
  1720. {
  1721. return &players[color];
  1722. }
  1723. else
  1724. {
  1725. tlog2 << "Warning: Cannot find info for player " << int(color) << std::endl;
  1726. return NULL;
  1727. }
  1728. }
  1729. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1730. {
  1731. if(!map->isInTheMap(src) || !map->isInTheMap(dest)) //check input
  1732. return false;
  1733. int3 hpos = hero->getPosition(false);
  1734. tribool blockLandSea; //true - blocks sea, false - blocks land, indeterminate - allows all
  1735. if (!hero->canWalkOnSea())
  1736. blockLandSea = (map->getTile(hpos).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1737. else
  1738. blockLandSea = boost::logic::indeterminate;
  1739. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1740. //graph initialization
  1741. std::vector< std::vector<CPathNode> > graph;
  1742. graph.resize(map->width);
  1743. for(size_t i=0; i<graph.size(); ++i)
  1744. {
  1745. graph[i].resize(map->height);
  1746. for(size_t j=0; j<graph[i].size(); ++j)
  1747. {
  1748. const TerrainTile *tinfo = &map->terrain[i][j][src.z];
  1749. CPathNode &node = graph[i][j];
  1750. node.accesible = !tinfo->blocked;
  1751. node.dist = -1;
  1752. node.theNodeBefore = NULL;
  1753. node.visited = false;
  1754. node.coord.x = i;
  1755. node.coord.y = j;
  1756. node.coord.z = dest.z;
  1757. if ((tinfo->tertype == TerrainTile::rock) //it's rock
  1758. || ((blockLandSea) && (tinfo->tertype == TerrainTile::water)) //it's sea and we cannot walk on sea
  1759. || ((!blockLandSea) && (tinfo->tertype != TerrainTile::water)) //it's land and we cannot walk on land
  1760. || !FoW[i][j][src.z] //tile is covered by the FoW
  1761. )
  1762. {
  1763. node.accesible = false;
  1764. }
  1765. }
  1766. }
  1767. //Special rules for the destination tile
  1768. {
  1769. const TerrainTile *t = &map->terrain[dest.x][dest.y][dest.z];
  1770. CPathNode &d = graph[dest.x][dest.y];
  1771. //tile may be blocked by blockvis / normal vis obj but it still must be accessible
  1772. if(t->visitable)
  1773. {
  1774. d.accesible = true; //for allowing visiting objects
  1775. }
  1776. if(blockLandSea && t->tertype == TerrainTile::water) //hero can walk only on land and dst lays on the water
  1777. {
  1778. size_t i = 0;
  1779. for(; i < t->visitableObjects.size(); i++)
  1780. if(t->visitableObjects[i]->ID == 8 || t->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1781. break;
  1782. d.accesible = (i < t->visitableObjects.size()); //dest is accessible only if there is boat/hero
  1783. }
  1784. else if(!blockLandSea && t->tertype != TerrainTile::water) //hero is moving by water
  1785. {
  1786. d.accesible = (t->siodmyTajemniczyBajt & 64) && !t->blocked; //tile is accessible if it's coastal and not blocked
  1787. }
  1788. }
  1789. //graph initialized
  1790. //initial tile - set cost on 0 and add to the queue
  1791. graph[src.x][src.y].dist = 0;
  1792. std::queue<CPathNode> mq;
  1793. mq.push(graph[src.x][src.y]);
  1794. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1795. std::vector<int3> neighbours;
  1796. neighbours.reserve(8);
  1797. while(!mq.empty())
  1798. {
  1799. CPathNode &cp = graph[mq.front().coord.x][mq.front().coord.y];
  1800. mq.pop();
  1801. if (cp.coord == dest) //it's destination tile
  1802. {
  1803. if (cp.dist < curDist) //that path is better than previous one
  1804. curDist = cp.dist;
  1805. continue;
  1806. }
  1807. else
  1808. {
  1809. if (cp.dist > curDist) //it's not dest and current length is greater than cost of already found path
  1810. continue;
  1811. }
  1812. //add accessible neighbouring nodes to the queue
  1813. getNeighbours(map->getTile(cp.coord), cp.coord, neighbours, boost::logic::indeterminate);
  1814. for(unsigned int i=0; i < neighbours.size(); i++)
  1815. {
  1816. CPathNode & dp = graph[neighbours[i].x][neighbours[i].y];
  1817. if(dp.accesible)
  1818. {
  1819. int cost = getMovementCost(hero,cp.coord,dp.coord,hero->movement - cp.dist);
  1820. if((dp.dist==-1 || (dp.dist > cp.dist + cost)) && dp.accesible && checkForVisitableDir(cp.coord, dp.coord) && checkForVisitableDir(dp.coord, cp.coord))
  1821. {
  1822. dp.dist = cp.dist + cost;
  1823. dp.theNodeBefore = &cp;
  1824. mq.push(dp);
  1825. }
  1826. }
  1827. }
  1828. }
  1829. CPathNode *curNode = &graph[dest.x][dest.y];
  1830. if(!curNode->theNodeBefore) //destination is not accessible
  1831. return false;
  1832. //fill ret with found path
  1833. ret.nodes.clear();
  1834. while(curNode->coord != graph[src.x][src.y].coord)
  1835. {
  1836. ret.nodes.push_back(*curNode);
  1837. curNode = curNode->theNodeBefore;
  1838. }
  1839. ret.nodes.push_back(graph[src.x][src.y]);
  1840. return true;
  1841. }
  1842. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  1843. {
  1844. assert(hero);
  1845. if(src.x < 0)
  1846. src = hero->getPosition(false);
  1847. if(movement < 0)
  1848. movement = hero->movement;
  1849. out.hero = hero;
  1850. out.hpos = src;
  1851. if(!map->isInTheMap(src)/* || !map->isInTheMap(dest)*/) //check input
  1852. {
  1853. tlog1 << "CGameState::calculatePaths: Hero outside the map? How dare you...\n";
  1854. return;
  1855. }
  1856. tribool onLand; //true - blocks sea, false - blocks land, indeterminate - allows all
  1857. if (!hero->canWalkOnSea())
  1858. onLand = (map->getTile(src).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1859. else
  1860. onLand = boost::logic::indeterminate;
  1861. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1862. //graph initialization
  1863. CGPathNode ***graph = out.nodes;
  1864. for(size_t i=0; i < out.sizes.x; ++i)
  1865. {
  1866. for(size_t j=0; j < out.sizes.y; ++j)
  1867. {
  1868. for(size_t k=0; k < out.sizes.z; ++k)
  1869. {
  1870. const TerrainTile *tinfo = &map->terrain[i][j][k];
  1871. CGPathNode &node = graph[i][j][k];
  1872. node.accessible = (tinfo->blocked ? CGPathNode::BLOCKED : CGPathNode::ACCESSIBLE);
  1873. node.turns = 0xff;
  1874. node.moveRemains = 0;
  1875. node.coord.x = i;
  1876. node.coord.y = j;
  1877. node.coord.z = k;
  1878. node.land = tinfo->tertype != TerrainTile::water;
  1879. node.theNodeBefore = NULL;
  1880. if ( tinfo->tertype == TerrainTile::rock//it's rock
  1881. || onLand && !node.land //it's sea and we cannot walk on sea
  1882. || !onLand && node.land //it's land and we cannot walk on land
  1883. || !FoW[i][j][k] //tile is covered by the FoW
  1884. )
  1885. {
  1886. node.accessible = CGPathNode::BLOCKED;
  1887. }
  1888. else if(tinfo->visitable)
  1889. {
  1890. for(size_t ii = 0; ii < tinfo->visitableObjects.size(); ii++)
  1891. {
  1892. if(tinfo->visitableObjects[ii]->blockVisit)
  1893. {
  1894. node.accessible = CGPathNode::BLOCKVIS;
  1895. break;
  1896. }
  1897. else
  1898. node.accessible = CGPathNode::VISITABLE;
  1899. }
  1900. }
  1901. if(onLand && !node.land) //hero can walk only on land and tile lays on the water
  1902. {
  1903. size_t i = 0;
  1904. for(; i < tinfo->visitableObjects.size(); i++)
  1905. if(tinfo->visitableObjects[i]->ID == 8 || tinfo->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1906. break;
  1907. if(i < tinfo->visitableObjects.size())
  1908. node.accessible = CGPathNode::BLOCKVIS; //dest is accessible only if there is boat/hero
  1909. }
  1910. else if(!onLand && tinfo->tertype != TerrainTile::water) //hero is moving by water
  1911. {
  1912. if((tinfo->siodmyTajemniczyBajt & 64) && !tinfo->blocked)
  1913. node.accessible = CGPathNode::VISITABLE; //tile is accessible if it's coastal and not blocked
  1914. }
  1915. }
  1916. }
  1917. }
  1918. //graph initialized
  1919. //initial tile - set cost on 0 and add to the queue
  1920. graph[src.x][src.y][src.z].turns = 0;
  1921. graph[src.x][src.y][src.z].moveRemains = movement;
  1922. std::queue<CGPathNode*> mq;
  1923. mq.push(&graph[src.x][src.y][src.z]);
  1924. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1925. std::vector<int3> neighbours;
  1926. neighbours.reserve(8);
  1927. while(!mq.empty())
  1928. {
  1929. CGPathNode *cp = mq.front();
  1930. mq.pop();
  1931. const TerrainTile &ct = map->getTile(cp->coord);
  1932. int movement = cp->moveRemains, turn = cp->turns;
  1933. if(!movement)
  1934. {
  1935. movement = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  1936. turn++;
  1937. }
  1938. //add accessible neighbouring nodes to the queue
  1939. getNeighbours(ct, cp->coord, neighbours, boost::logic::indeterminate);
  1940. for(unsigned int i=0; i < neighbours.size(); i++)
  1941. {
  1942. const int3 &n = neighbours[i]; //current neighbor
  1943. CGPathNode & dp = graph[n.x][n.y][n.z];
  1944. if( !checkForVisitableDir(cp->coord, dp.coord)
  1945. || !checkForVisitableDir(dp.coord, cp->coord)
  1946. || dp.accessible == CGPathNode::BLOCKED )
  1947. {
  1948. continue;
  1949. }
  1950. int cost = getMovementCost(hero, cp->coord, dp.coord, movement);
  1951. int remains = movement - cost;
  1952. if(remains < 0)
  1953. {
  1954. //occurs rarely, when hero with low movepoints tries to go leave the road
  1955. turn++;
  1956. movement = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  1957. cost = getMovementCost(hero, cp->coord, dp.coord, movement); //cost must be updated, movement points changed :(
  1958. remains = movement - cost;
  1959. }
  1960. if(dp.turns==0xff //we haven't been here before
  1961. || dp.turns > turn
  1962. || (dp.turns >= turn && dp.moveRemains < remains)) //this route is faster
  1963. {
  1964. assert(&dp != cp->theNodeBefore); //two tiles can't point to each other
  1965. dp.moveRemains = remains;
  1966. dp.turns = turn;
  1967. dp.theNodeBefore = cp;
  1968. if(dp.accessible == CGPathNode::ACCESSIBLE)
  1969. {
  1970. mq.push(&dp);
  1971. }
  1972. }
  1973. } //neighbours loop
  1974. } //queue loop
  1975. }
  1976. bool CGameState::isVisible(int3 pos, int player)
  1977. {
  1978. if(player == 255) //neutral player
  1979. return false;
  1980. return players[player].fogOfWarMap[pos.x][pos.y][pos.z];
  1981. }
  1982. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  1983. {
  1984. if(player == 255) //neutral player
  1985. return false;
  1986. //object is visible when at least one blocked tile is visible
  1987. for(int fx=0; fx<8; ++fx)
  1988. {
  1989. for(int fy=0; fy<6; ++fy)
  1990. {
  1991. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  1992. if(map->isInTheMap(pos)
  1993. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  1994. && isVisible(pos, player) )
  1995. return true;
  1996. }
  1997. }
  1998. return false;
  1999. }
  2000. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  2001. {
  2002. const TerrainTile * pom = &map->getTile(dst);
  2003. return checkForVisitableDir(src, pom, dst);
  2004. }
  2005. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  2006. {
  2007. for(unsigned int b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  2008. {
  2009. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  2010. continue;
  2011. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  2012. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  2013. {
  2014. return false;
  2015. }
  2016. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  2017. {
  2018. return false;
  2019. }
  2020. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  2021. {
  2022. return false;
  2023. }
  2024. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  2025. {
  2026. return false;
  2027. }
  2028. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  2029. {
  2030. return false;
  2031. }
  2032. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  2033. {
  2034. return false;
  2035. }
  2036. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  2037. {
  2038. return false;
  2039. }
  2040. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  2041. {
  2042. return false;
  2043. }
  2044. }
  2045. return true;
  2046. }
  2047. std::pair<ui32, ui32> BattleInfo::calculateDmgRange(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge)
  2048. {
  2049. float attackDefenseBonus,
  2050. minDmg = attacker->creature->damageMin * attacker->amount,
  2051. maxDmg = attacker->creature->damageMax * attacker->amount;
  2052. if(attacker->creature->idNumber == 149) //arrow turret
  2053. {
  2054. switch(attacker->position)
  2055. {
  2056. case -2: //keep
  2057. minDmg = 15;
  2058. maxDmg = 15;
  2059. break;
  2060. case -3: case -4: //turrets
  2061. minDmg = 7.5f;
  2062. maxDmg = 7.5f;
  2063. break;
  2064. }
  2065. }
  2066. if(attacker->hasFeatureOfType(StackFeature::SIEGE_WEAPON) && attacker->creature->idNumber != 149) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  2067. { //minDmg and maxDmg are multiplied by hero attack + 1
  2068. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  2069. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  2070. }
  2071. if(attacker->hasFeatureOfType(StackFeature::GENERAL_ATTACK_REDUCTION))
  2072. {
  2073. attackDefenseBonus = attacker->Attack() * (attacker->valOfFeatures(StackFeature::GENERAL_ATTACK_REDUCTION, -1024) / 100.0f) - defender->Defense();
  2074. }
  2075. else
  2076. {
  2077. attackDefenseBonus = attacker->Attack() - defender->Defense();
  2078. }
  2079. //calculating total attack/defense skills modifier
  2080. if(!shooting && attacker->hasFeatureOfType(StackFeature::ATTACK_BONUS, 0)) //bloodlust handling (etc.)
  2081. {
  2082. attackDefenseBonus += attacker->valOfFeatures(StackFeature::ATTACK_BONUS, 0);
  2083. }
  2084. if(shooting && attacker->hasFeatureOfType(StackFeature::ATTACK_BONUS, 1)) //precision handling (etc.)
  2085. {
  2086. attackDefenseBonus += attacker->valOfFeatures(StackFeature::ATTACK_BONUS, 1);
  2087. }
  2088. if(attacker->getEffect(55)) //slayer handling
  2089. {
  2090. std::vector<int> affectedIds;
  2091. switch(attacker->getEffect(55)->level)
  2092. {
  2093. case 3: //expert
  2094. {
  2095. affectedIds.push_back(40); //giant
  2096. affectedIds.push_back(41); //titan
  2097. affectedIds.push_back(152); //lord of thunder
  2098. } //continue adding ...
  2099. case 2: //advanced
  2100. {
  2101. affectedIds.push_back(12); //angel
  2102. affectedIds.push_back(13); //archangel
  2103. affectedIds.push_back(54); //devil
  2104. affectedIds.push_back(55); //arch devil
  2105. affectedIds.push_back(150); //supreme archangel
  2106. affectedIds.push_back(153); //antichrist
  2107. } //continue adding ...
  2108. case 0: case 1: //none and basic
  2109. {
  2110. affectedIds.push_back(26); //green dragon
  2111. affectedIds.push_back(27); //gold dragon
  2112. affectedIds.push_back(82); //red dragon
  2113. affectedIds.push_back(83); //black dragon
  2114. affectedIds.push_back(96); //behemot
  2115. affectedIds.push_back(97); //ancient behemot
  2116. affectedIds.push_back(110); //hydra
  2117. affectedIds.push_back(111); //chaos hydra
  2118. affectedIds.push_back(132); //azure dragon
  2119. affectedIds.push_back(133); //crystal dragon
  2120. affectedIds.push_back(134); //faerie dragon
  2121. affectedIds.push_back(135); //rust dragon
  2122. affectedIds.push_back(151); //diamond dragon
  2123. affectedIds.push_back(154); //blood dragon
  2124. affectedIds.push_back(155); //darkness dragon
  2125. affectedIds.push_back(156); //ghost behemoth
  2126. affectedIds.push_back(157); //hell hydra
  2127. break;
  2128. }
  2129. }
  2130. for(unsigned int g=0; g<affectedIds.size(); ++g)
  2131. {
  2132. if(defender->creature->idNumber == affectedIds[g])
  2133. {
  2134. attackDefenseBonus += VLC->spellh->spells[55].powers[attacker->getEffect(55)->level];
  2135. break;
  2136. }
  2137. }
  2138. }
  2139. float dmgBonusMultiplier = 1.0f;
  2140. //applying jousting bonus
  2141. if( attacker->hasFeatureOfType(StackFeature::JOUSTING) && !defender->hasFeatureOfType(StackFeature::CHARGE_IMMUNITY) )
  2142. dmgBonusMultiplier += charge * 0.05f;
  2143. //bonus from attack/defense skills
  2144. if(attackDefenseBonus < 0) //decreasing dmg
  2145. {
  2146. if(0.02f * (-attackDefenseBonus) > 0.3f)
  2147. {
  2148. dmgBonusMultiplier += -0.3f;
  2149. }
  2150. else
  2151. {
  2152. dmgBonusMultiplier += 0.02f * attackDefenseBonus;
  2153. }
  2154. }
  2155. else //increasing dmg
  2156. {
  2157. if(0.05f * attackDefenseBonus > 4.0f)
  2158. {
  2159. dmgBonusMultiplier += 4.0f;
  2160. }
  2161. else
  2162. {
  2163. dmgBonusMultiplier += 0.05f * attackDefenseBonus;
  2164. }
  2165. }
  2166. //handling secondary abilities and artifacts giving premies to them
  2167. if(attackerHero)
  2168. {
  2169. if(shooting)
  2170. {
  2171. switch(attackerHero->getSecSkillLevel(1)) //archery
  2172. {
  2173. case 1: //basic
  2174. dmgBonusMultiplier += 0.1f;
  2175. break;
  2176. case 2: //advanced
  2177. dmgBonusMultiplier += 0.25f;
  2178. break;
  2179. case 3: //expert
  2180. dmgBonusMultiplier += 0.5f;
  2181. break;
  2182. }
  2183. if(attackerHero->getSecSkillLevel(1) > 0) //non-none level
  2184. {
  2185. //apply artifact premy to archery
  2186. dmgBonusMultiplier += attackerHero->valOfBonuses(HeroBonus::SECONDARY_SKILL_PREMY, 1) / 100.0f;
  2187. }
  2188. }
  2189. else
  2190. {
  2191. switch(attackerHero->getSecSkillLevel(22)) //offense
  2192. {
  2193. case 1: //basic
  2194. dmgBonusMultiplier += 0.1f;
  2195. break;
  2196. case 2: //advanced
  2197. dmgBonusMultiplier += 0.2f;
  2198. break;
  2199. case 3: //expert
  2200. dmgBonusMultiplier += 0.3f;
  2201. break;
  2202. }
  2203. }
  2204. }
  2205. if(defendingHero)
  2206. {
  2207. switch(defendingHero->getSecSkillLevel(23)) //armorer
  2208. {
  2209. case 1: //basic
  2210. dmgBonusMultiplier *= 0.95f;
  2211. break;
  2212. case 2: //advanced
  2213. dmgBonusMultiplier *= 0.9f;
  2214. break;
  2215. case 3: //expert
  2216. dmgBonusMultiplier *= 0.85f;
  2217. break;
  2218. }
  2219. }
  2220. //handling hate effect
  2221. if( attacker->hasFeatureOfType(StackFeature::HATE, defender->creature->idNumber) )
  2222. dmgBonusMultiplier += 0.5f;
  2223. //handling spell effects
  2224. if(!shooting && defender->hasFeatureOfType(StackFeature::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  2225. {
  2226. dmgBonusMultiplier *= float(defender->valOfFeatures(StackFeature::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0f;
  2227. }
  2228. else if(shooting && defender->hasFeatureOfType(StackFeature::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  2229. {
  2230. dmgBonusMultiplier *= float(defender->valOfFeatures(StackFeature::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0f;
  2231. }
  2232. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  2233. {
  2234. dmgBonusMultiplier *= 0.8f * float(VLC->spellh->spells[42].powers[attacker->getEffect(42)->level]); //the second factor is 1 or 0
  2235. }
  2236. minDmg *= dmgBonusMultiplier;
  2237. maxDmg *= dmgBonusMultiplier;
  2238. if(attacker->getEffect(42)) //curse handling (rest)
  2239. {
  2240. minDmg -= VLC->spellh->spells[42].powers[attacker->getEffect(42)->level];
  2241. return std::make_pair(int(minDmg), int(minDmg));
  2242. }
  2243. else if(attacker->getEffect(41)) //bless handling
  2244. {
  2245. maxDmg += VLC->spellh->spells[41].powers[attacker->getEffect(41)->level];
  2246. return std::make_pair(int(maxDmg), int(maxDmg));
  2247. }
  2248. else
  2249. {
  2250. return std::make_pair(int(minDmg), int(maxDmg));
  2251. }
  2252. tlog1 << "We are too far in calculateDmg...\n";
  2253. return std::make_pair(0, 0);
  2254. }
  2255. ui32 BattleInfo::calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge)
  2256. {
  2257. std::pair<ui32, ui32> range = calculateDmgRange(attacker, defender, attackerHero, defendingHero, shooting, charge);
  2258. if(range.first != range.second)
  2259. return range.first + rand() % (range.second - range.first + 1);
  2260. else
  2261. return range.first;
  2262. }
  2263. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  2264. {
  2265. for(unsigned int i=0; i<stacks.size();i++)//setting casualties
  2266. {
  2267. const CStack * const st = stacks[i];
  2268. si32 killed = (st->alive() ? st->baseAmount - st->amount : st->baseAmount);
  2269. amax(killed, 0);
  2270. casualties[!st->attackerOwned][st->creature->idNumber] += killed;
  2271. }
  2272. }
  2273. si8 CGameState::battleMaxSpellLevel()
  2274. {
  2275. if(!curB) //there is not battle
  2276. {
  2277. tlog1 << "si8 CGameState::maxSpellLevel() call when there is no battle!" << std::endl;
  2278. throw "si8 CGameState::maxSpellLevel() call when there is no battle!";
  2279. }
  2280. si8 levelLimit = SPELL_LEVELS;
  2281. const CGHeroInstance *h1 = getHero(curB->hero1);
  2282. if(h1)
  2283. {
  2284. for(std::list<HeroBonus>::const_iterator i = h1->bonuses.begin(); i != h1->bonuses.end(); i++)
  2285. if(i->type == HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2286. amin(levelLimit, i->val);
  2287. }
  2288. const CGHeroInstance *h2 = getHero(curB->hero2);
  2289. if(h2)
  2290. {
  2291. for(std::list<HeroBonus>::const_iterator i = h2->bonuses.begin(); i != h2->bonuses.end(); i++)
  2292. if(i->type == HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2293. amin(levelLimit, i->val);
  2294. }
  2295. return levelLimit;
  2296. }
  2297. std::set<CStack*> BattleInfo::getAttackedCreatures(const CSpell * s, const CGHeroInstance * caster, int destinationTile)
  2298. {
  2299. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, caster->getSpellSchoolLevel(s));
  2300. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
  2301. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  2302. if(s->id == 24 || s->id == 25 || s->id == 26) //death ripple, destroy undead and Armageddon
  2303. {
  2304. for(int it=0; it<stacks.size(); ++it)
  2305. {
  2306. if((s->id == 24 && !stacks[it]->creature->isUndead()) //death ripple
  2307. || (s->id == 25 && stacks[it]->creature->isUndead()) //destroy undead
  2308. || (s->id == 26) //Armageddon
  2309. )
  2310. {
  2311. if(stacks[it]->alive())
  2312. attackedCres.insert(stacks[it]);
  2313. }
  2314. }
  2315. }
  2316. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_1") != std::string::npos
  2317. || VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_2") != std::string::npos) //spell to be cast on a specific creature but massive on expert
  2318. {
  2319. if(caster->getSpellSchoolLevel(s) < 3) /*not expert */
  2320. {
  2321. CStack * st = getStackT(destinationTile, onlyAlive);
  2322. if(st)
  2323. attackedCres.insert(st);
  2324. }
  2325. else
  2326. {
  2327. for(int it=0; it<stacks.size(); ++it)
  2328. {
  2329. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  2330. if((VLC->spellh->spells[s->id].positiveness >= 0 && stacks[it]->owner == caster->tempOwner)
  2331. ||(VLC->spellh->spells[s->id].positiveness <= 0 && stacks[it]->owner != caster->tempOwner )
  2332. )
  2333. {
  2334. if(!onlyAlive || stacks[it]->alive())
  2335. attackedCres.insert(stacks[it]);
  2336. }
  2337. }
  2338. } //if(caster->getSpellSchoolLevel(s) < 3)
  2339. }
  2340. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET") != std::string::npos) //spell to be cast on one specific creature
  2341. {
  2342. CStack * st = getStackT(destinationTile, onlyAlive);
  2343. if(st)
  2344. attackedCres.insert(st);
  2345. }
  2346. else //custom range from attackedHexes
  2347. {
  2348. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  2349. {
  2350. CStack * st = getStackT(*it, onlyAlive);
  2351. if(st)
  2352. attackedCres.insert(st);
  2353. }
  2354. }
  2355. return attackedCres;
  2356. }
  2357. int BattleInfo::calculateSpellDuration(const CSpell * spell, const CGHeroInstance * caster)
  2358. {
  2359. switch(spell->id)
  2360. {
  2361. case 56: //frenzy
  2362. return 1;
  2363. default: //other spells
  2364. return caster->getPrimSkillLevel(2) + caster->valOfBonuses(HeroBonus::SPELL_DURATION);
  2365. }
  2366. }
  2367. CStack * BattleInfo::generateNewStack(const CGHeroInstance * owner, int creatureID, int amount, int stackID, bool attackerOwned, int slot, int /*TerrainTile::EterrainType*/ terrain, int position) const
  2368. {
  2369. CStack * ret = new CStack(&VLC->creh->creatures[creatureID], amount, attackerOwned ? side1 : side2, stackID, attackerOwned, slot);
  2370. if(owner)
  2371. {
  2372. ret->features.push_back(makeFeature(StackFeature::SPEED_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->valOfBonuses(HeroBonus::STACKS_SPEED), StackFeature::BONUS_FROM_HERO));
  2373. //base luck/morale calculations
  2374. ret->morale = owner->getCurrentMorale(slot, false);
  2375. ret->luck = owner->getCurrentLuck(slot, false);
  2376. //other bonuses
  2377. ret->features.push_back(makeFeature(StackFeature::ATTACK_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->getPrimSkillLevel(0), StackFeature::BONUS_FROM_HERO));
  2378. ret->features.push_back(makeFeature(StackFeature::DEFENCE_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->getPrimSkillLevel(1), StackFeature::BONUS_FROM_HERO));
  2379. if ( owner->hasBonusOfType(HeroBonus::STACK_HEALTH_PERCENT) ) // e.g. Elixir of Life
  2380. ret->features.push_back(makeFeature(StackFeature::HP_BONUS, StackFeature::WHOLE_BATTLE, 0,
  2381. (ret->creature->hitPoints * owner->valOfBonuses(HeroBonus::STACK_HEALTH_PERCENT)) / 100,
  2382. StackFeature::BONUS_FROM_HERO));
  2383. if (owner->hasBonusOfType(HeroBonus::HP_REGENERATION)) // e.g. Elixir of Life
  2384. ret->features.push_back(makeFeature(StackFeature::HP_REGENERATION, StackFeature::WHOLE_BATTLE, 0,
  2385. owner->valOfBonuses(HeroBonus::HP_REGENERATION), StackFeature::BONUS_FROM_HERO));
  2386. if (owner->hasBonusOfType(HeroBonus::LEVEL_SPELL_IMMUNITY)) // e.g. Power of the Dragon Father
  2387. ret->features.push_back(makeFeature(StackFeature::LEVEL_SPELL_IMMUNITY, StackFeature::WHOLE_BATTLE, 0,
  2388. owner->valOfBonuses(HeroBonus::LEVEL_SPELL_IMMUNITY), StackFeature::BONUS_FROM_HERO));
  2389. ret->features.push_back(makeFeature(StackFeature::HP_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->valOfBonuses(HeroBonus::STACK_HEALTH), StackFeature::BONUS_FROM_HERO));
  2390. ret->firstHPleft = ret->MaxHealth();
  2391. }
  2392. else
  2393. {
  2394. ret->morale = 0;
  2395. ret->luck = 0;
  2396. }
  2397. //native terrain bonuses
  2398. int faction = ret->creature->faction;
  2399. if(faction >= 0 && VLC->heroh->nativeTerrains[faction] == terrain)
  2400. {
  2401. ret->features.push_back(makeFeature(StackFeature::SPEED_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2402. ret->features.push_back(makeFeature(StackFeature::ATTACK_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2403. ret->features.push_back(makeFeature(StackFeature::DEFENCE_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2404. }
  2405. ret->position = position;
  2406. return ret;
  2407. }
  2408. ui32 BattleInfo::getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  2409. {
  2410. ui32 ret = VLC->spellh->spells[sp->id].costs[caster->getSpellSchoolLevel(sp)];
  2411. //checking for friendly stacks reducing cost of the spell
  2412. si32 manaReduction = 0;
  2413. for(int g=0; g<stacks.size(); ++g)
  2414. {
  2415. if( stacks[g]->owner == caster->tempOwner && stacks[g]->hasFeatureOfType(StackFeature::CHANGES_SPELL_COST_FOR_ALLY) )
  2416. {
  2417. amin(manaReduction, stacks[g]->valOfFeatures(StackFeature::CHANGES_SPELL_COST_FOR_ALLY));
  2418. }
  2419. }
  2420. return ret + manaReduction;
  2421. }
  2422. int BattleInfo::hexToWallPart(int hex) const
  2423. {
  2424. if(siege == 0) //there is no battle!
  2425. return -1;
  2426. static const std::pair<int, int> attackable[] = //potentially attackable parts of wall
  2427. {std::make_pair(50, 0), std::make_pair(183, 1), std::make_pair(182, 2), std::make_pair(130, 3),
  2428. std::make_pair(62, 4), std::make_pair(29, 5), std::make_pair(12, 6), std::make_pair(95, 7), std::make_pair(96, 7)};
  2429. for(int g = 0; g < ARRAY_COUNT(attackable); ++g)
  2430. {
  2431. if(attackable[g].first == hex)
  2432. return attackable[g].second;
  2433. }
  2434. return -1; //not found!
  2435. }
  2436. std::pair<const CStack *, int> BattleInfo::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  2437. {
  2438. bool ac[BFIELD_SIZE];
  2439. std::set<int> occupyable;
  2440. getAccessibilityMap(ac, closest->hasFeatureOfType(StackFeature::DOUBLE_WIDE), closest->attackerOwned, false, occupyable, closest->hasFeatureOfType(StackFeature::FLYING), closest->ID);
  2441. int predecessor[BFIELD_SIZE], dist[BFIELD_SIZE];
  2442. makeBFS(closest->position, ac, predecessor, dist, closest->hasFeatureOfType(StackFeature::DOUBLE_WIDE), closest->attackerOwned, closest->hasFeatureOfType(StackFeature::FLYING), true);
  2443. std::vector< std::pair< std::pair<int, int>, const CStack *> > stackPairs; //pairs <<distance, hex>, stack>
  2444. for(int g=0; g<BFIELD_SIZE; ++g)
  2445. {
  2446. const CStack * atG = getStackT(g);
  2447. if(!atG || atG->ID == closest->ID) //if there is not stack or we are the closest one
  2448. continue;
  2449. if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  2450. {
  2451. if(predecessor[g] == -1) //TODO: is it really the best solution?
  2452. continue;
  2453. stackPairs.push_back( std::make_pair( std::make_pair(dist[predecessor[g]], g), atG) );
  2454. }
  2455. }
  2456. if(stackPairs.size() > 0)
  2457. {
  2458. std::vector< std::pair< std::pair<int, int>, const CStack *> > minimalPairs;
  2459. minimalPairs.push_back(stackPairs[0]);
  2460. for(int b=1; b<stackPairs.size(); ++b)
  2461. {
  2462. if(stackPairs[b].first.first < minimalPairs[0].first.first)
  2463. {
  2464. minimalPairs.clear();
  2465. minimalPairs.push_back(stackPairs[b]);
  2466. }
  2467. else if(stackPairs[b].first.first == minimalPairs[0].first.first)
  2468. {
  2469. minimalPairs.push_back(stackPairs[b]);
  2470. }
  2471. }
  2472. std::pair< std::pair<int, int>, const CStack *> minPair = minimalPairs[minimalPairs.size()/2];
  2473. return std::make_pair(minPair.second, predecessor[minPair.first.second]);
  2474. }
  2475. return std::make_pair<const CStack * , int>(NULL, -1);
  2476. }
  2477. bool CGameState::battleCanShoot(int ID, int dest)
  2478. {
  2479. if(!curB)
  2480. return false;
  2481. const CStack *our = curB->getStack(ID),
  2482. *dst = curB->getStackT(dest);
  2483. if(!our || !dst) return false;
  2484. const CGHeroInstance * ourHero = battleGetOwner(our->ID);
  2485. if(our->hasFeatureOfType(StackFeature::FORGETFULL)) //forgetfulness
  2486. return false;
  2487. if(our->hasFeatureOfType(StackFeature::SHOOTER)//it's shooter
  2488. && our->owner != dst->owner
  2489. && dst->alive()
  2490. && (!curB->isStackBlocked(ID) ||
  2491. ( ourHero && ourHero->hasBonusOfType(HeroBonus::FREE_SHOOTING) ) )
  2492. && our->shots
  2493. )
  2494. return true;
  2495. return false;
  2496. }
  2497. const CStack * BattleInfo::getNextStack() const
  2498. {
  2499. std::vector<const CStack *> hlp;
  2500. getStackQueue(hlp, 1, -1);
  2501. if(hlp.size())
  2502. return hlp[0];
  2503. else
  2504. return NULL;
  2505. }
  2506. static const CStack *takeStack(std::vector<const CStack *> &st, int &curside, int turn)
  2507. {
  2508. const CStack *ret = NULL;
  2509. unsigned i, //fastest stack
  2510. j; //fastest stack of the other side
  2511. for(i = 0; i < st.size(); i++)
  2512. if(st[i])
  2513. break;
  2514. //no stacks left
  2515. if(i == st.size())
  2516. return NULL;
  2517. const CStack *fastest = st[i], *other = NULL;
  2518. int bestSpeed = fastest->Speed(turn);
  2519. if(fastest->attackerOwned != curside)
  2520. {
  2521. ret = fastest;
  2522. }
  2523. else
  2524. {
  2525. for(j = i + 1; j < st.size(); j++)
  2526. {
  2527. if(!st[j]) continue;
  2528. if(st[j]->attackerOwned != curside || st[j]->Speed(turn) != bestSpeed)
  2529. break;
  2530. }
  2531. if(j >= st.size())
  2532. {
  2533. ret = fastest;
  2534. }
  2535. else
  2536. {
  2537. other = st[j];
  2538. if(other->Speed(turn) != bestSpeed)
  2539. ret = fastest;
  2540. else
  2541. ret = other;
  2542. }
  2543. }
  2544. assert(ret);
  2545. if(ret == fastest)
  2546. st[i] = NULL;
  2547. else
  2548. st[j] = NULL;
  2549. curside = ret->attackerOwned;
  2550. return ret;
  2551. }
  2552. void BattleInfo::getStackQueue( std::vector<const CStack *> &out, int howMany, int turn /*= 0*/, int lastMoved /*= -1*/ ) const
  2553. {
  2554. //we'll split creatures with remaining movement to 4 parts
  2555. std::vector<const CStack *> phase[4]; //0 - turrets/catapult, 1 - normal (unmoved) creatures, other war machines, 2 - waited cres that had morale, 3 - rest of waited cres
  2556. int toMove = 0; //how many stacks still has move
  2557. const CStack *active = getStack(activeStack);
  2558. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  2559. if(!turn && active && active->willMove() && !vstd::contains(active->state, WAITING))
  2560. {
  2561. out.push_back(active);
  2562. if(out.size() == howMany)
  2563. return;
  2564. }
  2565. for(unsigned int i=0; i<stacks.size(); ++i)
  2566. {
  2567. const CStack * const s = stacks[i];
  2568. if(turn <= 0 && !s->willMove() //we are considering current round and stack won't move
  2569. || turn > 0 && !s->canMove(turn) //stack won't be able to move in later rounds
  2570. || turn <= 0 && s == active) //it's active stack already added at the beginning of queue
  2571. {
  2572. continue;
  2573. }
  2574. int p = -1; //in which phase this tack will move?
  2575. if(turn <= 0 && vstd::contains(s->state, WAITING)) //consider waiting state only for ongoing round
  2576. {
  2577. if(vstd::contains(s->state, HAD_MORALE))
  2578. p = 2;
  2579. else
  2580. p = 3;
  2581. }
  2582. else if(s->creature->idNumber == 145 || s->creature->idNumber == 149) //catapult and turrets are first
  2583. {
  2584. p = 0;
  2585. }
  2586. else
  2587. {
  2588. p = 1;
  2589. }
  2590. phase[p].push_back(s);
  2591. toMove++;
  2592. }
  2593. for(int i = 0; i < 4; i++)
  2594. std::sort(phase[i].begin(), phase[i].end(), CMP_stack(i, turn > 0 ? turn : 0));
  2595. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  2596. out.push_back(phase[0][i]);
  2597. if(out.size() == howMany)
  2598. return;
  2599. if(lastMoved == -1)
  2600. {
  2601. if(active)
  2602. {
  2603. if(out.size() && out.front() == active)
  2604. lastMoved = active->attackerOwned;
  2605. else
  2606. lastMoved = active->attackerOwned;
  2607. }
  2608. else
  2609. {
  2610. lastMoved = 0;
  2611. }
  2612. }
  2613. int pi = 1;
  2614. while(out.size() < howMany)
  2615. {
  2616. const CStack *hlp = takeStack(phase[pi], lastMoved, turn);
  2617. if(!hlp)
  2618. {
  2619. pi++;
  2620. if(pi > 3)
  2621. {
  2622. //if(turn != 2)
  2623. getStackQueue(out, howMany, turn + 1, lastMoved);
  2624. return;
  2625. }
  2626. }
  2627. else
  2628. {
  2629. out.push_back(hlp);
  2630. }
  2631. }
  2632. }
  2633. int3 CPath::startPos() const
  2634. {
  2635. return nodes[nodes.size()-1].coord;
  2636. }
  2637. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  2638. {
  2639. if (mode==0)
  2640. {
  2641. for (unsigned int i=0;i<nodes.size();i++)
  2642. {
  2643. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2644. }
  2645. }
  2646. }
  2647. int3 CPath::endPos() const
  2648. {
  2649. return nodes[0].coord;
  2650. }
  2651. CGPathNode::CGPathNode()
  2652. :coord(-1,-1,-1)
  2653. {
  2654. accessible = 0;
  2655. land = 0;
  2656. moveRemains = 0;
  2657. turns = 255;
  2658. theNodeBefore = NULL;
  2659. }
  2660. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  2661. {
  2662. out.nodes.clear();
  2663. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  2664. if(!curnode->theNodeBefore)
  2665. return false;
  2666. while(curnode)
  2667. {
  2668. out.nodes.push_back(*curnode);
  2669. curnode = curnode->theNodeBefore;
  2670. }
  2671. return true;
  2672. }
  2673. CPathsInfo::CPathsInfo( const int3 &Sizes )
  2674. :sizes(Sizes)
  2675. {
  2676. nodes = new CGPathNode**[sizes.x];
  2677. for(int i = 0; i < sizes.x; i++)
  2678. {
  2679. nodes[i] = new CGPathNode*[sizes.y];
  2680. for (int j = 0; j < sizes.y; j++)
  2681. {
  2682. nodes[i][j] = new CGPathNode[sizes.z];
  2683. }
  2684. }
  2685. }
  2686. CPathsInfo::~CPathsInfo()
  2687. {
  2688. for(int i = 0; i < sizes.x; i++)
  2689. {
  2690. for (int j = 0; j < sizes.y; j++)
  2691. {
  2692. delete [] nodes[i][j];
  2693. }
  2694. delete [] nodes[i];
  2695. }
  2696. delete [] nodes;
  2697. }
  2698. int3 CGPath::startPos() const
  2699. {
  2700. return nodes[nodes.size()-1].coord;
  2701. }
  2702. int3 CGPath::endPos() const
  2703. {
  2704. return nodes[0].coord;
  2705. }
  2706. void CGPath::convert( ui8 mode )
  2707. {
  2708. if(mode==0)
  2709. {
  2710. for(unsigned int i=0;i<nodes.size();i++)
  2711. {
  2712. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2713. }
  2714. }
  2715. }
  2716. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  2717. {
  2718. switch(phase)
  2719. {
  2720. case 0: //catapult moves after turrets
  2721. return a->creature->idNumber < b->creature->idNumber; //catapult is 145 and turrets are 149
  2722. //TODO? turrets order
  2723. case 1: //fastest first, upper slot first
  2724. {
  2725. int as = a->Speed(turn), bs = b->Speed(turn);
  2726. if(as != bs)
  2727. return as > bs;
  2728. else
  2729. return a->slot < b->slot;
  2730. }
  2731. case 2: //fastest last, upper slot first
  2732. //TODO: should be replaced with order of receiving morale!
  2733. case 3: //fastest last, upper slot first
  2734. {
  2735. int as = a->Speed(turn), bs = b->Speed(turn);
  2736. if(as != bs)
  2737. return as < bs;
  2738. else
  2739. return a->slot < b->slot;
  2740. }
  2741. default:
  2742. assert(0);
  2743. return false;
  2744. }
  2745. }
  2746. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  2747. {
  2748. phase = Phase;
  2749. turn = Turn;
  2750. }
  2751. PlayerState::PlayerState()
  2752. : color(-1), currentSelection(0xffffffff)
  2753. {
  2754. }