CGameState.cpp 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349
  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. void MetaString::getLocalString(const std::pair<ui8,ui32> &txt, std::string &dst) const
  84. {
  85. int type = txt.first, ser = txt.second;
  86. if(type == ART_NAMES)
  87. {
  88. dst = VLC->arth->artifacts[ser].Name();
  89. }
  90. else if(type == CRE_PL_NAMES)
  91. {
  92. dst = VLC->creh->creatures[ser].namePl;
  93. }
  94. else if(type == MINE_NAMES)
  95. {
  96. dst = VLC->generaltexth->mines[ser].first;
  97. }
  98. else if(type == MINE_EVNTS)
  99. {
  100. dst = VLC->generaltexth->mines[ser].second;
  101. }
  102. else if(type == SPELL_NAME)
  103. {
  104. dst = VLC->spellh->spells[ser].name;
  105. }
  106. else if(type == CRE_SING_NAMES)
  107. {
  108. dst = VLC->creh->creatures[ser].nameSing;
  109. }
  110. else
  111. {
  112. std::vector<std::string> *vec;
  113. switch(type)
  114. {
  115. case GENERAL_TXT:
  116. vec = &VLC->generaltexth->allTexts;
  117. break;
  118. case XTRAINFO_TXT:
  119. vec = &VLC->generaltexth->xtrainfo;
  120. break;
  121. case OBJ_NAMES:
  122. vec = &VLC->generaltexth->names;
  123. break;
  124. case RES_NAMES:
  125. vec = &VLC->generaltexth->restypes;
  126. break;
  127. case ARRAY_TXT:
  128. vec = &VLC->generaltexth->arraytxt;
  129. break;
  130. case CREGENS:
  131. vec = &VLC->generaltexth->creGens;
  132. break;
  133. case CREGENS4:
  134. vec = &VLC->generaltexth->creGens4;
  135. break;
  136. case ADVOB_TXT:
  137. vec = &VLC->generaltexth->advobtxt;
  138. break;
  139. case ART_EVNTS:
  140. vec = &VLC->generaltexth->artifEvents;
  141. break;
  142. case SEC_SKILL_NAME:
  143. vec = &VLC->generaltexth->skillName;
  144. break;
  145. }
  146. dst = (*vec)[ser];
  147. }
  148. }
  149. DLL_EXPORT void MetaString::toString(std::string &dst) const
  150. {
  151. size_t exSt = 0, loSt = 0, nums = 0;
  152. dst.clear();
  153. for(size_t i=0;i<message.size();++i)
  154. {//TEXACT_STRING, TLOCAL_STRING, TNUMBER, TREPLACE_ESTRING, TREPLACE_LSTRING, TREPLACE_NUMBER
  155. switch(message[i])
  156. {
  157. case TEXACT_STRING:
  158. dst += exactStrings[exSt++];
  159. break;
  160. case TLOCAL_STRING:
  161. {
  162. std::string hlp;
  163. getLocalString(localStrings[loSt++], hlp);
  164. dst += hlp;
  165. }
  166. break;
  167. case TNUMBER:
  168. dst += boost::lexical_cast<std::string>(numbers[nums++]);
  169. break;
  170. case TREPLACE_ESTRING:
  171. dst.replace(dst.find("%s"), 2, exactStrings[exSt++]);
  172. break;
  173. case TREPLACE_LSTRING:
  174. {
  175. std::string hlp;
  176. getLocalString(localStrings[loSt++], hlp);
  177. dst.replace(dst.find("%s"), 2, hlp);
  178. }
  179. break;
  180. case TREPLACE_NUMBER:
  181. dst.replace(dst.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  182. break;
  183. default:
  184. tlog1 << "MetaString processing error!\n";
  185. break;
  186. }
  187. }
  188. }
  189. static CGObjectInstance * createObject(int id, int subid, int3 pos, int owner)
  190. {
  191. CGObjectInstance * nobj;
  192. switch(id)
  193. {
  194. case HEROI_TYPE: //hero
  195. {
  196. CGHeroInstance * nobj = new CGHeroInstance();
  197. nobj->pos = pos;
  198. nobj->tempOwner = owner;
  199. nobj->subID = subid;
  200. //nobj->initHero(ran);
  201. return nobj;
  202. }
  203. case TOWNI_TYPE: //town
  204. nobj = new CGTownInstance;
  205. break;
  206. default: //rest of objects
  207. nobj = new CGObjectInstance;
  208. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  209. break;
  210. }
  211. nobj->ID = id;
  212. nobj->subID = subid;
  213. if(!nobj->defInfo)
  214. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  215. nobj->pos = pos;
  216. //nobj->state = NULL;//new CLuaObjectScript();
  217. nobj->tempOwner = owner;
  218. nobj->info = NULL;
  219. nobj->defInfo->id = id;
  220. nobj->defInfo->subid = subid;
  221. //assigning defhandler
  222. if(nobj->ID==HEROI_TYPE || nobj->ID==TOWNI_TYPE)
  223. return nobj;
  224. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  225. return nobj;
  226. }
  227. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  228. {
  229. for(unsigned int g=0; g<stacks.size(); ++g)
  230. {
  231. if(stacks[g]->ID == stackID && (!onlyAlive || stacks[g]->alive()))
  232. return stacks[g];
  233. }
  234. return NULL;
  235. }
  236. CStack * BattleInfo::getStackT(int tileID, bool onlyAlive)
  237. {
  238. for(unsigned int g=0; g<stacks.size(); ++g)
  239. {
  240. if(stacks[g]->position == tileID
  241. || (stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  242. || (stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  243. {
  244. if(!onlyAlive || stacks[g]->alive())
  245. {
  246. return stacks[g];
  247. }
  248. }
  249. }
  250. return NULL;
  251. }
  252. void BattleInfo::getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<int> & occupyable, bool flying, int stackToOmmit)
  253. {
  254. memset(accessibility, 1, BFIELD_SIZE); //initialize array with trues
  255. for(unsigned int g=0; g<stacks.size(); ++g)
  256. {
  257. if(!stacks[g]->alive() || stacks[g]->ID==stackToOmmit) //we don't want to lock position of this stack
  258. continue;
  259. accessibility[stacks[g]->position] = false;
  260. if(stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE)) //if it's a double hex creature
  261. {
  262. if(stacks[g]->attackerOwned)
  263. accessibility[stacks[g]->position-1] = false;
  264. else
  265. accessibility[stacks[g]->position+1] = false;
  266. }
  267. }
  268. //obstacles
  269. for(unsigned int b=0; b<obstacles.size(); ++b)
  270. {
  271. std::vector<int> blocked = VLC->heroh->obstacles[obstacles[b].ID].getBlocked(obstacles[b].pos);
  272. for(unsigned int c=0; c<blocked.size(); ++c)
  273. {
  274. if(blocked[c] >=0 && blocked[c] < BFIELD_SIZE)
  275. accessibility[blocked[c]] = false;
  276. }
  277. }
  278. if(addOccupiable && twoHex)
  279. {
  280. std::set<int> rem; //tiles to unlock
  281. for(int h=0; h<BFIELD_HEIGHT; ++h)
  282. {
  283. for(int w=1; w<BFIELD_WIDTH-1; ++w)
  284. {
  285. int hex = h * BFIELD_WIDTH + w;
  286. if(!isAccessible(hex, accessibility, twoHex, attackerOwned, flying, true)
  287. && (attackerOwned ? isAccessible(hex+1, accessibility, twoHex, attackerOwned, flying, true) : isAccessible(hex-1, accessibility, twoHex, attackerOwned, flying, true) )
  288. )
  289. rem.insert(hex);
  290. }
  291. }
  292. occupyable = rem;
  293. /*for(std::set<int>::const_iterator it = rem.begin(); it != rem.end(); ++it)
  294. {
  295. accessibility[*it] = true;
  296. }*/
  297. }
  298. }
  299. bool BattleInfo::isAccessible(int hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos)
  300. {
  301. if(flying && !lastPos)
  302. return true;
  303. if(twoHex)
  304. {
  305. //if given hex is accessible and appropriate adjacent one is free too
  306. return accessibility[hex] && accessibility[hex + (attackerOwned ? -1 : 1 )];
  307. }
  308. else
  309. {
  310. return accessibility[hex];
  311. }
  312. }
  313. void BattleInfo::makeBFS(int start, bool *accessibility, int *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying) //both pointers must point to the at least 187-elements int arrays
  314. {
  315. //inits
  316. for(int b=0; b<BFIELD_SIZE; ++b)
  317. predecessor[b] = -1;
  318. for(int g=0; g<BFIELD_SIZE; ++g)
  319. dists[g] = 100000000;
  320. std::queue<int> hexq; //bfs queue
  321. hexq.push(start);
  322. dists[hexq.front()] = 0;
  323. int curNext = -1; //for bfs loop only (helper var)
  324. while(!hexq.empty()) //bfs loop
  325. {
  326. int curHex = hexq.front();
  327. std::vector<int> neighbours = neighbouringTiles(curHex);
  328. hexq.pop();
  329. for(unsigned int nr=0; nr<neighbours.size(); nr++)
  330. {
  331. curNext = neighbours[nr]; //if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  332. if(!isAccessible(curNext, accessibility, twoHex, attackerOwned, flying, dists[curHex]+1 == dists[curNext]) || (dists[curHex]+1)>=dists[curNext])
  333. continue;
  334. hexq.push(curNext);
  335. dists[curNext] = dists[curHex] + 1;
  336. predecessor[curNext] = curHex;
  337. }
  338. }
  339. };
  340. std::vector<int> BattleInfo::getAccessibility(int stackID, bool addOccupiable)
  341. {
  342. std::vector<int> ret;
  343. bool ac[BFIELD_SIZE];
  344. CStack *s = getStack(stackID);
  345. std::set<int> occupyable;
  346. getAccessibilityMap(ac, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, addOccupiable, occupyable, s->hasFeatureOfType(StackFeature::FLYING), stackID);
  347. int pr[BFIELD_SIZE], dist[BFIELD_SIZE];
  348. makeBFS(s->position, ac, pr, dist, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, s->hasFeatureOfType(StackFeature::FLYING));
  349. if(s->hasFeatureOfType(StackFeature::DOUBLE_WIDE))
  350. {
  351. if(!addOccupiable)
  352. {
  353. std::vector<int> rem;
  354. for(int b=0; b<BFIELD_SIZE; ++b)
  355. {
  356. if( ac[b] && !(s->attackerOwned ? ac[b-1] : ac[b+1]))
  357. {
  358. rem.push_back(b);
  359. }
  360. }
  361. for(unsigned int g=0; g<rem.size(); ++g)
  362. {
  363. ac[rem[g]] = false;
  364. }
  365. //removing accessibility for side hexes
  366. for(int v=0; v<BFIELD_SIZE; ++v)
  367. if(s->attackerOwned ? (v%BFIELD_WIDTH)==1 : (v%BFIELD_WIDTH)==(BFIELD_WIDTH - 2))
  368. ac[v] = false;
  369. }
  370. }
  371. for(int i=0; i < BFIELD_SIZE ; ++i)
  372. if(
  373. ( ( !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
  374. || (vstd::contains(occupyable, i) && ( dist[ i + (s->attackerOwned ? 1 : -1 ) ] <= s->Speed() ) &&
  375. ac[i + (s->attackerOwned ? 1 : -1 )] ) //it's occupyable and we can reach adjacent hex
  376. )
  377. {
  378. ret.push_back(i);
  379. }
  380. return ret;
  381. }
  382. bool BattleInfo::isStackBlocked(int ID)
  383. {
  384. CStack *our = getStack(ID);
  385. if(our->hasFeatureOfType(StackFeature::SIEGE_WEAPON)) //siege weapons cannot be blocked
  386. return true;
  387. for(unsigned int i=0; i<stacks.size();i++)
  388. {
  389. if( !stacks[i]->alive()
  390. || stacks[i]->owner==our->owner
  391. )
  392. continue; //we omit dead and allied stacks
  393. if(stacks[i]->hasFeatureOfType(StackFeature::DOUBLE_WIDE))
  394. {
  395. if( mutualPosition(stacks[i]->position, our->position) >= 0
  396. || mutualPosition(stacks[i]->position + (stacks[i]->attackerOwned ? -1 : 1), our->position) >= 0)
  397. return true;
  398. }
  399. else
  400. {
  401. if( mutualPosition(stacks[i]->position, our->position) >= 0 )
  402. return true;
  403. }
  404. }
  405. return false;
  406. }
  407. signed char BattleInfo::mutualPosition(int hex1, int hex2)
  408. {
  409. if(hex2 == hex1 - ( (hex1/17)%2 ? 18 : 17 )) //top left
  410. return 0;
  411. if(hex2 == hex1 - ( (hex1/17)%2 ? 17 : 16 )) //top right
  412. return 1;
  413. if(hex2 == hex1 - 1 && hex1%17 != 0) //left
  414. return 5;
  415. if(hex2 == hex1 + 1 && hex1%17 != 16) //right
  416. return 2;
  417. if(hex2 == hex1 + ( (hex1/17)%2 ? 16 : 17 )) //bottom left
  418. return 4;
  419. if(hex2 == hex1 + ( (hex1/17)%2 ? 17 : 18 )) //bottom right
  420. return 3;
  421. return -1;
  422. }
  423. std::vector<int> BattleInfo::neighbouringTiles(int hex)
  424. {
  425. #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);}
  426. std::vector<int> ret;
  427. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 18 : 17 ));
  428. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 17 : 16 ));
  429. CHECK_AND_PUSH(hex - 1);
  430. CHECK_AND_PUSH(hex + 1);
  431. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 16 : 17 ));
  432. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 17 : 18 ));
  433. #undef CHECK_AND_PUSH
  434. return ret;
  435. }
  436. std::pair< std::vector<int>, int > BattleInfo::getPath(int start, int dest, bool*accessibility, bool flyingCreature, bool twoHex, bool attackerOwned)
  437. {
  438. int predecessor[BFIELD_SIZE]; //for getting the Path
  439. int dist[BFIELD_SIZE]; //calculated distances
  440. makeBFS(start, accessibility, predecessor, dist, twoHex, attackerOwned, flyingCreature);
  441. if(predecessor[dest] == -1) //cannot reach destination
  442. {
  443. return std::make_pair(std::vector<int>(), 0);
  444. }
  445. //making the Path
  446. std::vector<int> path;
  447. int curElem = dest;
  448. while(curElem != start)
  449. {
  450. path.push_back(curElem);
  451. curElem = predecessor[curElem];
  452. }
  453. return std::make_pair(path, dist[dest]);
  454. }
  455. int CStack::valOfFeatures(StackFeature::ECombatFeatures type, int subtype) const
  456. {
  457. int ret = 0;
  458. if(subtype == -1024) //any subtype
  459. {
  460. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  461. if(i->type == type)
  462. ret += i->value;
  463. }
  464. else //given subtype
  465. {
  466. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  467. if(i->type == type && i->subtype == subtype)
  468. ret += i->value;
  469. }
  470. return ret;
  471. }
  472. bool CStack::hasFeatureOfType(StackFeature::ECombatFeatures type, int subtype) const
  473. {
  474. if(subtype == -1024) //any subtype
  475. {
  476. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  477. if(i->type == type)
  478. return true;
  479. }
  480. else //given subtype
  481. {
  482. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  483. if(i->type == type && i->subtype == subtype)
  484. return true;
  485. }
  486. return false;
  487. }
  488. CStack::CStack(CCreature * C, int A, int O, int I, bool AO, int S)
  489. :ID(I), creature(C), amount(A), baseAmount(A), firstHPleft(C->hitPoints), owner(O), slot(S), attackerOwned(AO), position(-1),
  490. counterAttacks(1), shots(C->shots), features(C->abilities)
  491. {
  492. //additional retaliations
  493. for(int h=0; h<C->abilities.size(); ++h)
  494. {
  495. if(C->abilities[h].type == StackFeature::ADDITIONAL_RETALIATION)
  496. {
  497. counterAttacks += C->abilities[h].value;
  498. }
  499. }
  500. //alive state indication
  501. state.insert(ALIVE);
  502. }
  503. ui32 CStack::Speed() const
  504. {
  505. if(hasFeatureOfType(StackFeature::SIEGE_WEAPON)) //war machnes cannot move
  506. return 0;
  507. int speed = creature->speed;
  508. speed += valOfFeatures(StackFeature::SPEED_BONUS);
  509. int percentBonus = 0;
  510. for(int g=0; g<features.size(); ++g)
  511. {
  512. if(features[g].type == StackFeature::SPEED_BONUS)
  513. {
  514. percentBonus += features[g].additionalInfo;
  515. }
  516. }
  517. if(percentBonus < 0)
  518. {
  519. speed = (abs(percentBonus) * speed)/100;
  520. }
  521. else
  522. {
  523. speed = ((100 + percentBonus) * speed)/100;
  524. }
  525. //bind effect check
  526. if(getEffect(72))
  527. {
  528. return 0;
  529. }
  530. return speed;
  531. }
  532. const CStack::StackEffect * CStack::getEffect(ui16 id) const
  533. {
  534. for (unsigned int i=0; i< effects.size(); i++)
  535. if(effects[i].id == id)
  536. return &effects[i];
  537. return NULL;
  538. }
  539. ui8 CStack::howManyEffectsSet(ui16 id) const
  540. {
  541. ui8 ret = 0;
  542. for (unsigned int i=0; i< effects.size(); i++)
  543. if(effects[i].id == id) //effect found
  544. {
  545. ++ret;
  546. }
  547. return ret;
  548. }
  549. si8 CStack::Morale() const
  550. {
  551. si8 ret = morale;
  552. if(hasFeatureOfType(StackFeature::NON_LIVING) || hasFeatureOfType(StackFeature::UNDEAD) || hasFeatureOfType(StackFeature::NO_MORALE))
  553. return 0;
  554. ret += valOfFeatures(StackFeature::MORALE_BONUS); //mirth & sorrow & other
  555. if(hasFeatureOfType(StackFeature::SELF_MORALE)) //eg. minotaur
  556. {
  557. ret = std::max<si8>(ret, +1);
  558. }
  559. if(ret > 3) ret = 3;
  560. if(ret < -3) ret = -3;
  561. return ret;
  562. }
  563. si8 CStack::Luck() const
  564. {
  565. si8 ret = luck;
  566. if(hasFeatureOfType(StackFeature::NO_LUCK))
  567. return 0;
  568. ret += valOfFeatures(StackFeature::LUCK_BONUS); //fortune & misfortune & other
  569. if(hasFeatureOfType(StackFeature::SELF_LUCK)) //eg. halfling
  570. {
  571. ret = std::max<si8>(ret, +1);
  572. }
  573. if(ret > 3) ret = 3;
  574. if(ret < -3) ret = -3;
  575. return ret;
  576. }
  577. si32 CStack::Attack() const
  578. {
  579. si32 ret = creature->attack; //value to be returned
  580. if(hasFeatureOfType(StackFeature::IN_FRENZY)) //frenzy for attacker
  581. {
  582. ret += (VLC->spellh->spells[56].powers[getEffect(56)->level]/100.0) * Defense(false);
  583. }
  584. ret += valOfFeatures(StackFeature::ATTACK_BONUS);
  585. return ret;
  586. }
  587. si32 CStack::Defense(bool withFrenzy /*= true*/) const
  588. {
  589. si32 ret = creature->defence;
  590. if(withFrenzy && getEffect(56)) //frenzy for defender
  591. {
  592. return 0;
  593. }
  594. ret += valOfFeatures(StackFeature::DEFENCE_BONUS);
  595. return ret;
  596. }
  597. ui16 CStack::MaxHealth() const
  598. {
  599. return creature->hitPoints + valOfFeatures(StackFeature::HP_BONUS);
  600. }
  601. bool CStack::willMove()
  602. {
  603. return !vstd::contains(state, DEFENDING)
  604. && !vstd::contains(state, MOVED)
  605. && alive()
  606. && ! hasFeatureOfType(StackFeature::NOT_ACTIVE); //eg. Ammo Cart
  607. }
  608. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native, int player, const CTown *town, std::map<ui32,CGHeroInstance *> &available) const
  609. {
  610. CGHeroInstance *ret = NULL;
  611. if(player<0 || player>=PLAYER_LIMIT)
  612. {
  613. tlog1 << "Cannot pick hero for " << town->Name() << ". Wrong owner!\n";
  614. return NULL;
  615. }
  616. std::vector<CGHeroInstance *> pool;
  617. if(native)
  618. {
  619. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  620. {
  621. if(pavailable.find(i->first)->second & 1<<player
  622. && i->second->type->heroType/2 == town->typeID)
  623. {
  624. pool.push_back(i->second);
  625. }
  626. }
  627. if(!pool.size())
  628. {
  629. tlog1 << "Cannot pick native hero for " << player << ". Picking any...\n";
  630. return pickHeroFor(false, player, town, available);
  631. }
  632. else
  633. {
  634. ret = pool[rand()%pool.size()];
  635. }
  636. }
  637. else
  638. {
  639. int sum=0, r;
  640. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  641. {
  642. if(pavailable.find(i->first)->second & 1<<player)
  643. {
  644. pool.push_back(i->second);
  645. sum += i->second->type->heroClass->selectionProbability[town->typeID];
  646. }
  647. }
  648. if(!pool.size())
  649. {
  650. tlog1 << "There are no heroes available for player " << player<<"!\n";
  651. return NULL;
  652. }
  653. r = rand()%sum;
  654. for(unsigned int i=0; i<pool.size(); i++)
  655. {
  656. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  657. if(r<0)
  658. ret = pool[i];
  659. }
  660. if(!ret)
  661. ret = pool.back();
  662. }
  663. available.erase(ret->subID);
  664. return ret;
  665. }
  666. //void CGameState::apply(CPack * pack)
  667. //{
  668. // while(!mx->try_lock())
  669. // boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  670. // //applyNL(pack);
  671. // mx->unlock();
  672. //}
  673. int CGameState::pickHero(int owner)
  674. {
  675. int h=-1;
  676. if(!map->getHero(h = scenarioOps->getIthPlayersSettings(owner).hero,0) && h>=0) //we haven't used selected hero
  677. return h;
  678. int f = scenarioOps->getIthPlayersSettings(owner).castle;
  679. int i=0;
  680. do //try to find free hero of our faction
  681. {
  682. i++;
  683. h = scenarioOps->getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  684. } while( map->getHero(h) && i<175);
  685. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  686. {
  687. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  688. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  689. if(!map->getHero(j))
  690. h=j;
  691. }
  692. return h;
  693. }
  694. CGHeroInstance *CGameState::getHero(int objid)
  695. {
  696. if(objid<0 || objid>=map->objects.size() || map->objects[objid]->ID!=HEROI_TYPE)
  697. return NULL;
  698. return static_cast<CGHeroInstance *>(map->objects[objid]);
  699. }
  700. CGTownInstance *CGameState::getTown(int objid)
  701. {
  702. if(objid<0 || objid>=map->objects.size())
  703. return NULL;
  704. return static_cast<CGTownInstance *>(map->objects[objid]);
  705. }
  706. std::pair<int,int> CGameState::pickObject(CGObjectInstance *obj)
  707. {
  708. switch(obj->ID)
  709. {
  710. case 65: //random artifact
  711. return std::pair<int,int>(5,(ran()%136)+7); //tylko sensowny zakres - na poczatku sa katapulty itp, na koncu specjalne i blanki
  712. case 66: //random treasure artifact
  713. return std::pair<int,int>(5,VLC->arth->treasures[ran()%VLC->arth->treasures.size()]->id);
  714. case 67: //random minor artifact
  715. return std::pair<int,int>(5,VLC->arth->minors[ran()%VLC->arth->minors.size()]->id);
  716. case 68: //random major artifact
  717. return std::pair<int,int>(5,VLC->arth->majors[ran()%VLC->arth->majors.size()]->id);
  718. case 69: //random relic artifact
  719. return std::pair<int,int>(5,VLC->arth->relics[ran()%VLC->arth->relics.size()]->id);
  720. case 70: //random hero
  721. {
  722. return std::pair<int,int>(HEROI_TYPE,pickHero(obj->tempOwner));
  723. }
  724. case 71: //random monster
  725. {
  726. int r;
  727. do
  728. {
  729. r = ran()%197;
  730. } while (vstd::contains(VLC->creh->notUsedMonsters,r));
  731. return std::pair<int,int>(54,r);
  732. }
  733. case 72: //random monster lvl1
  734. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  735. case 73: //random monster lvl2
  736. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  737. case 74: //random monster lvl3
  738. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  739. case 75: //random monster lvl4
  740. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  741. case 76: //random resource
  742. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  743. case 77: //random town
  744. {
  745. int align = (static_cast<CGTownInstance*>(obj))->alignment,
  746. f;
  747. if(align>PLAYER_LIMIT-1)//same as owner / random
  748. {
  749. if(obj->tempOwner > PLAYER_LIMIT-1)
  750. f = -1; //random
  751. else
  752. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  753. }
  754. else
  755. {
  756. f = scenarioOps->getIthPlayersSettings(align).castle;
  757. }
  758. if(f<0) f = ran()%VLC->townh->towns.size();
  759. return std::pair<int,int>(TOWNI_TYPE,f);
  760. }
  761. case 162: //random monster lvl5
  762. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  763. case 163: //random monster lvl6
  764. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  765. case 164: //random monster lvl7
  766. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  767. case 216: //random dwelling
  768. {
  769. int faction = ran()%F_NUMBER;
  770. CCreGen2ObjInfo* info = static_cast<CCreGen2ObjInfo*>(obj->info);
  771. if (info->asCastle)
  772. {
  773. for(unsigned int i=0;i<map->objects.size();i++)
  774. {
  775. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  776. {
  777. randomizeObject(map->objects[i]); //we have to randomize the castle first
  778. faction = map->objects[i]->subID;
  779. break;
  780. }
  781. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  782. {
  783. faction = map->objects[i]->subID;
  784. break;
  785. }
  786. }
  787. }
  788. else
  789. {
  790. while((!(info->castles[0]&(1<<faction))))
  791. {
  792. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  793. break;
  794. faction = ran()%F_NUMBER;
  795. }
  796. }
  797. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  798. int cid = VLC->townh->towns[faction].basicCreatures[level];
  799. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  800. if(VLC->objh->cregens[i]==cid)
  801. return std::pair<int,int>(17,i);
  802. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  803. return std::pair<int,int>(17,0);
  804. }
  805. case 217:
  806. {
  807. int faction = ran()%F_NUMBER;
  808. CCreGenObjInfo* info = static_cast<CCreGenObjInfo*>(obj->info);
  809. if (info->asCastle)
  810. {
  811. for(unsigned int i=0;i<map->objects.size();i++)
  812. {
  813. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  814. {
  815. randomizeObject(map->objects[i]); //we have to randomize the castle first
  816. faction = map->objects[i]->subID;
  817. break;
  818. }
  819. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  820. {
  821. faction = map->objects[i]->subID;
  822. break;
  823. }
  824. }
  825. }
  826. else
  827. {
  828. while((!(info->castles[0]&(1<<faction))))
  829. {
  830. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  831. break;
  832. faction = ran()%F_NUMBER;
  833. }
  834. }
  835. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  836. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  837. if(VLC->objh->cregens[i]==cid)
  838. return std::pair<int,int>(17,i);
  839. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  840. return std::pair<int,int>(17,0);
  841. }
  842. case 218:
  843. {
  844. CCreGen3ObjInfo* info = static_cast<CCreGen3ObjInfo*>(obj->info);
  845. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  846. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  847. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  848. if(VLC->objh->cregens[i]==cid)
  849. return std::pair<int,int>(17,i);
  850. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  851. return std::pair<int,int>(17,0);
  852. }
  853. }
  854. return std::pair<int,int>(-1,-1);
  855. }
  856. void CGameState::randomizeObject(CGObjectInstance *cur)
  857. {
  858. std::pair<int,int> ran = pickObject(cur);
  859. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  860. {
  861. if(cur->ID==TOWNI_TYPE) //town - set def
  862. {
  863. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  864. if(t->hasCapitol())
  865. t->defInfo = capitols[t->subID];
  866. else if(t->hasFort())
  867. t->defInfo = forts[t->subID];
  868. else
  869. t->defInfo = villages[t->subID];
  870. }
  871. return;
  872. }
  873. else if(ran.first==HEROI_TYPE)//special code for hero
  874. {
  875. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  876. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  877. cur->ID = ran.first;
  878. h->portrait = cur->subID = ran.second;
  879. h->type = VLC->heroh->heroes[ran.second];
  880. map->heroes.push_back(h);
  881. return; //TODO: maybe we should do something with definfo?
  882. }
  883. else if(ran.first==TOWNI_TYPE)//special code for town
  884. {
  885. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  886. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  887. cur->ID = ran.first;
  888. cur->subID = ran.second;
  889. t->town = &VLC->townh->towns[ran.second];
  890. if(t->hasCapitol())
  891. t->defInfo = capitols[t->subID];
  892. else if(t->hasFort())
  893. t->defInfo = forts[t->subID];
  894. else
  895. t->defInfo = villages[t->subID];
  896. map->towns.push_back(t);
  897. return;
  898. }
  899. //we have to replace normal random object
  900. cur->ID = ran.first;
  901. cur->subID = ran.second;
  902. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  903. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  904. if(!cur->defInfo)
  905. {
  906. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  907. return;
  908. }
  909. map->addBlockVisTiles(cur);
  910. }
  911. int CGameState::getDate(int mode) const
  912. {
  913. int temp;
  914. switch (mode)
  915. {
  916. case 0:
  917. return day;
  918. break;
  919. case 1:
  920. temp = (day)%7;
  921. if (temp)
  922. return temp;
  923. else return 7;
  924. break;
  925. case 2:
  926. temp = ((day-1)/7)+1;
  927. if (!(temp%4))
  928. return 4;
  929. else
  930. return (temp%4);
  931. break;
  932. case 3:
  933. return ((day-1)/28)+1;
  934. break;
  935. }
  936. return 0;
  937. }
  938. CGameState::CGameState()
  939. {
  940. mx = new boost::shared_mutex();
  941. map = NULL;
  942. curB = NULL;
  943. scenarioOps = NULL;
  944. applierGs = new CGSApplier;
  945. }
  946. CGameState::~CGameState()
  947. {
  948. delete mx;
  949. delete map;
  950. delete curB;
  951. delete scenarioOps;
  952. delete applierGs;
  953. }
  954. void CGameState::init(StartInfo * si, Mapa * map, int Seed)
  955. {
  956. day = 0;
  957. seed = Seed;
  958. ran.seed((boost::int32_t)seed);
  959. scenarioOps = si;
  960. this->map = map;
  961. loadTownDInfos();
  962. //picking random factions for players
  963. for(unsigned int i=0;i<scenarioOps->playerInfos.size();i++)
  964. {
  965. if(scenarioOps->playerInfos[i].castle==-1)
  966. {
  967. int f;
  968. do
  969. {
  970. f = ran()%F_NUMBER;
  971. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  972. scenarioOps->playerInfos[i].castle = f;
  973. }
  974. }
  975. //randomizing objects
  976. for(unsigned int no=0; no<map->objects.size(); ++no)
  977. {
  978. randomizeObject(map->objects[no]);
  979. if(map->objects[no]->ID==26)
  980. {
  981. map->objects[no]->defInfo->handler=NULL;
  982. }
  983. map->objects[no]->hoverName = VLC->generaltexth->names[map->objects[no]->ID];
  984. }
  985. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  986. /*********give starting hero****************************************/
  987. for(int i=0;i<PLAYER_LIMIT;i++)
  988. {
  989. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==CMapHeader::RoE))
  990. {
  991. int3 hpos = map->players[i].posOfMainTown;
  992. hpos.x+=1;// hpos.y+=1;
  993. int j;
  994. for(j=0; j<scenarioOps->playerInfos.size(); j++) //don't add unsigned here - we are refering to the variable above
  995. if(scenarioOps->playerInfos[j].color == i)
  996. break;
  997. if(j == scenarioOps->playerInfos.size())
  998. continue;
  999. int h=pickHero(i);
  1000. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(HEROI_TYPE,h,hpos,i));
  1001. nnn->id = map->objects.size();
  1002. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  1003. for(unsigned int o=0;o<map->towns.size();o++) //find main town
  1004. {
  1005. if(map->towns[o]->pos == hpos)
  1006. {
  1007. map->towns[o]->visitingHero = nnn;
  1008. nnn->visitedTown = map->towns[o];
  1009. nnn->inTownGarrison = false;
  1010. break;
  1011. }
  1012. }
  1013. nnn->initHero();
  1014. map->heroes.push_back(nnn);
  1015. map->objects.push_back(nnn);
  1016. map->addBlockVisTiles(nnn);
  1017. }
  1018. }
  1019. /*********creating players entries in gs****************************************/
  1020. for (unsigned int i=0; i<scenarioOps->playerInfos.size();i++)
  1021. {
  1022. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  1023. ins.second.color=ins.first;
  1024. ins.second.serial=i;
  1025. ins.second.human = scenarioOps->playerInfos[i].human;
  1026. players.insert(ins);
  1027. }
  1028. /******************RESOURCES****************************************************/
  1029. //TODO: computer player should receive other amount of resource than computer (depending on difficulty)
  1030. std::vector<int> startres;
  1031. std::ifstream tis("config/startres.txt");
  1032. int k;
  1033. for (int j=0;j<scenarioOps->difficulty;j++)
  1034. {
  1035. tis >> k;
  1036. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1037. tis>>k;
  1038. }
  1039. tis >> k;
  1040. for (int i=0;i<RESOURCE_QUANTITY;i++)
  1041. {
  1042. tis >> k;
  1043. startres.push_back(k);
  1044. }
  1045. tis.close();
  1046. tis.clear();
  1047. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1048. {
  1049. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1050. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1051. (*i).second.resources[x] = startres[x];
  1052. }
  1053. tis.open("config/resources.txt");
  1054. tis >> k;
  1055. int pom;
  1056. for(int i=0;i<k;i++)
  1057. {
  1058. tis >> pom;
  1059. resVals.push_back(pom);
  1060. }
  1061. /*************************HEROES************************************************/
  1062. std::set<int> hids;
  1063. for(unsigned int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1064. if(map->allowedHeroes[i])
  1065. hids.insert(i);
  1066. for (unsigned int i=0; i<map->heroes.size();i++) //heroes instances initialization
  1067. {
  1068. if (map->heroes[i]->getOwner()<0)
  1069. {
  1070. tlog2 << "Warning - hero with uninitialized owner!\n";
  1071. continue;
  1072. }
  1073. CGHeroInstance * vhi = (map->heroes[i]);
  1074. vhi->initHero();
  1075. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1076. hids.erase(vhi->subID);
  1077. }
  1078. for(unsigned int i=0; i<map->predefinedHeroes.size(); i++)
  1079. {
  1080. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1081. continue;
  1082. map->predefinedHeroes[i]->initHero();
  1083. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1084. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1085. hids.erase(map->predefinedHeroes[i]->subID);
  1086. }
  1087. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go into the pool
  1088. {
  1089. CGHeroInstance * vhi = new CGHeroInstance();
  1090. vhi->initHero(hid);
  1091. hpool.heroesPool[hid] = vhi;
  1092. hpool.pavailable[hid] = 0xff;
  1093. }
  1094. for(unsigned int i=0; i<map->disposedHeroes.size(); i++)
  1095. {
  1096. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1097. }
  1098. /*************************FOG**OF**WAR******************************************/
  1099. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1100. {
  1101. k->second.fogOfWarMap.resize(map->width);
  1102. for(int g=0; g<map->width; ++g)
  1103. k->second.fogOfWarMap[g].resize(map->height);
  1104. for(int g=-0; g<map->width; ++g)
  1105. for(int h=0; h<map->height; ++h)
  1106. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1107. for(int g=0; g<map->width; ++g)
  1108. for(int h=0; h<map->height; ++h)
  1109. for(int v=0; v<map->twoLevel+1; ++v)
  1110. k->second.fogOfWarMap[g][h][v] = 0;
  1111. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1112. {
  1113. if(obj->tempOwner != k->first) continue; //not a flagged object
  1114. int3 objCenter = obj->getSightCenter();
  1115. int radious = obj->getSightRadious();
  1116. for (int xd = std::max<int>(objCenter.x - radious , 0); xd <= std::min<int>(objCenter.x + radious, map->width - 1); xd++)
  1117. {
  1118. for (int yd = std::max<int>(objCenter.y - radious, 0); yd <= std::min<int>(objCenter.y + radious, map->height - 1); yd++)
  1119. {
  1120. double distance = objCenter.dist2d(int3(xd,yd,objCenter.z)) - 0.5;
  1121. if(distance <= radious)
  1122. k->second.fogOfWarMap[xd][yd][objCenter.z] = 1;
  1123. }
  1124. }
  1125. }
  1126. //for(int xd=0; xd<map->width; ++xd) //revealing part of map around heroes
  1127. //{
  1128. // for(int yd=0; yd<map->height; ++yd)
  1129. // {
  1130. // for(int ch=0; ch<k->second.heroes.size(); ++ch)
  1131. // {
  1132. // int deltaX = (k->second.heroes[ch]->getPosition(false).x-xd)*(k->second.heroes[ch]->getPosition(false).x-xd);
  1133. // int deltaY = (k->second.heroes[ch]->getPosition(false).y-yd)*(k->second.heroes[ch]->getPosition(false).y-yd);
  1134. // if(deltaX+deltaY<k->second.heroes[ch]->getSightDistance()*k->second.heroes[ch]->getSightDistance())
  1135. // k->second.fogOfWarMap[xd][yd][k->second.heroes[ch]->getPosition(false).z] = 1;
  1136. // }
  1137. // }
  1138. //}
  1139. //starting bonus
  1140. if(si->playerInfos[k->second.serial].bonus==brandom)
  1141. si->playerInfos[k->second.serial].bonus = ran()%3;
  1142. switch(si->playerInfos[k->second.serial].bonus)
  1143. {
  1144. case bgold:
  1145. k->second.resources[6] += 500 + (ran()%6)*100;
  1146. break;
  1147. case bresource:
  1148. {
  1149. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1150. if(res == 127)
  1151. {
  1152. k->second.resources[0] += 5 + ran()%6;
  1153. k->second.resources[2] += 5 + ran()%6;
  1154. }
  1155. else
  1156. {
  1157. k->second.resources[res] += 3 + ran()%4;
  1158. }
  1159. break;
  1160. }
  1161. case bartifact:
  1162. {
  1163. if(!k->second.heroes.size())
  1164. {
  1165. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1166. break;
  1167. }
  1168. CArtifact *toGive;
  1169. do
  1170. {
  1171. toGive = VLC->arth->treasures[ran() % VLC->arth->treasures.size()];
  1172. } while (!map->allowedArtifact[toGive->id]);
  1173. CGHeroInstance *hero = k->second.heroes[0];
  1174. std::vector<ui16>::iterator slot = vstd::findFirstNot(hero->artifWorn,toGive->possibleSlots);
  1175. if(slot!=toGive->possibleSlots.end())
  1176. {
  1177. hero->artifWorn[*slot] = toGive->id;
  1178. hero->recreateArtBonuses();
  1179. }
  1180. else
  1181. hero->artifacts.push_back(toGive->id);
  1182. }
  1183. }
  1184. }
  1185. /****************************TOWNS************************************************/
  1186. for (unsigned int i=0;i<map->towns.size();i++)
  1187. {
  1188. CGTownInstance * vti =(map->towns[i]);
  1189. if(!vti->town)
  1190. vti->town = &VLC->townh->towns[vti->subID];
  1191. if (vti->name.length()==0) // if town hasn't name we draw it
  1192. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1193. //init buildings
  1194. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1195. {
  1196. vti->builtBuildings.erase(-50);
  1197. vti->builtBuildings.insert(10);
  1198. vti->builtBuildings.insert(5);
  1199. vti->builtBuildings.insert(30);
  1200. if(ran()%2)
  1201. vti->builtBuildings.insert(31);
  1202. }
  1203. //init spells
  1204. vti->spells.resize(SPELL_LEVELS);
  1205. CSpell *s;
  1206. for(unsigned int z=0; z<vti->obligatorySpells.size();z++)
  1207. {
  1208. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1209. vti->spells[s->level-1].push_back(s->id);
  1210. vti->possibleSpells -= s->id;
  1211. }
  1212. while(vti->possibleSpells.size())
  1213. {
  1214. ui32 total=0, sel=-1;
  1215. for(unsigned int ps=0;ps<vti->possibleSpells.size();ps++)
  1216. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1217. int r = (total)? ran()%total : -1;
  1218. for(unsigned int ps=0; ps<vti->possibleSpells.size();ps++)
  1219. {
  1220. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1221. if(r<0)
  1222. {
  1223. sel = ps;
  1224. break;
  1225. }
  1226. }
  1227. if(sel<0)
  1228. sel=0;
  1229. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1230. vti->spells[s->level-1].push_back(s->id);
  1231. vti->possibleSpells -= s->id;
  1232. }
  1233. //init garrisons
  1234. for (std::map<si32,std::pair<ui32,si32> >::iterator j=vti->army.slots.begin(); j!=vti->army.slots.end();j++)
  1235. {
  1236. if(j->second.first > 196 && j->second.first < 211)
  1237. {
  1238. if(j->second.first%2)
  1239. j->second.first = vti->town->basicCreatures[ (j->second.first-197) / 2 ];
  1240. else
  1241. j->second.first = vti->town->upgradedCreatures[ (j->second.first-197) / 2 ];
  1242. }
  1243. }
  1244. if(vti->getOwner() != 255)
  1245. getPlayer(vti->getOwner())->towns.push_back(vti);
  1246. }
  1247. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1248. {
  1249. if(k->first==-1 || k->first==255)
  1250. continue;
  1251. //init visiting and garrisoned heroes
  1252. for(unsigned int l=0; l<k->second.heroes.size();l++)
  1253. {
  1254. for(unsigned int m=0; m<k->second.towns.size();m++)
  1255. {
  1256. int3 vistile = k->second.towns[m]->pos; vistile.x--; //tile next to the entrance
  1257. if(vistile == k->second.heroes[l]->pos || k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1258. {
  1259. k->second.towns[m]->visitingHero = k->second.heroes[l];
  1260. k->second.heroes[l]->visitedTown = k->second.towns[m];
  1261. k->second.heroes[l]->inTownGarrison = false;
  1262. if(k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1263. k->second.heroes[l]->pos.x -= 1;
  1264. break;
  1265. }
  1266. }
  1267. }
  1268. }
  1269. for(unsigned int i=0; i<map->defy.size(); i++)
  1270. {
  1271. map->defy[i]->serial = i;
  1272. }
  1273. for(unsigned int i=0; i<map->objects.size(); i++)
  1274. {
  1275. map->objects[i]->initObj();
  1276. if(map->objects[i]->ID == 62) //prison also needs to initialize hero
  1277. static_cast<CGHeroInstance*>(map->objects[i])->initHero();
  1278. }
  1279. }
  1280. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1281. {
  1282. return true;
  1283. }
  1284. bool CGameState::battleCanFlee(int player)
  1285. {
  1286. if(!curB) //there is no battle
  1287. return false;
  1288. const CGHeroInstance *h1 = getHero(curB->hero1);
  1289. const CGHeroInstance *h2 = getHero(curB->hero2);
  1290. if(h1->hasBonusOfType(HeroBonus::ENEMY_CANT_ESCAPE) //eg. one of heroes is wearing shakles of war
  1291. || h2->hasBonusOfType(HeroBonus::ENEMY_CANT_ESCAPE))
  1292. return false;
  1293. return true;
  1294. }
  1295. int CGameState::battleGetStack(int pos, bool onlyAlive)
  1296. {
  1297. if(!curB)
  1298. return -1;
  1299. for(unsigned int g=0; g<curB->stacks.size(); ++g)
  1300. {
  1301. if((curB->stacks[g]->position == pos
  1302. || (curB->stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE)
  1303. &&( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos)
  1304. || (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos) )
  1305. ))
  1306. && (!onlyAlive || curB->stacks[g]->alive())
  1307. )
  1308. return curB->stacks[g]->ID;
  1309. }
  1310. return -1;
  1311. }
  1312. int CGameState::battleGetBattlefieldType(int3 tile)
  1313. {
  1314. if(tile==int3() && curB)
  1315. tile = curB->tile;
  1316. else if(tile==int3() && !curB)
  1317. return -1;
  1318. const std::vector <CGObjectInstance*> & objs = map->objects;
  1319. for(int g=0; g<objs.size(); ++g)
  1320. {
  1321. if( !objs[g] || objs[g]->pos.x - tile.x < 0 || objs[g]->pos.x - tile.x >= 8
  1322. || tile.y - objs[g]->pos.y + 5 < 0 || tile.y - objs[g]->pos.y + 5 >=6
  1323. || !objs[g]->coveringAt(objs[g]->pos.x - tile.x, tile.y - objs[g]->pos.y + 5)
  1324. ) //look only for objects covering given tile
  1325. continue;
  1326. switch(objs[g]->ID)
  1327. {
  1328. case 222: //clover field
  1329. return 19;
  1330. case 21: case 223: //cursed ground
  1331. return 22;
  1332. case 224: //evil fog
  1333. return 20;
  1334. case 225: //favourable winds
  1335. return 21;
  1336. case 226: //fiery fields
  1337. return 14;
  1338. case 227: //holy ground
  1339. return 18;
  1340. case 228: //lucid pools
  1341. return 17;
  1342. case 229: //magic clouds
  1343. return 16;
  1344. case 46: case 230: //magic plains
  1345. return 9;
  1346. case 231: //rocklands
  1347. return 15;
  1348. }
  1349. }
  1350. switch(map->terrain[tile.x][tile.y][tile.z].tertype)
  1351. {
  1352. case TerrainTile::dirt:
  1353. return rand()%3+3;
  1354. case TerrainTile::sand:
  1355. return 2; //TODO: coast support
  1356. case TerrainTile::grass:
  1357. return rand()%2+6;
  1358. case TerrainTile::snow:
  1359. return rand()%2+10;
  1360. case TerrainTile::swamp:
  1361. return 13;
  1362. case TerrainTile::rough:
  1363. return 23;
  1364. case TerrainTile::subterranean:
  1365. return 12;
  1366. case TerrainTile::lava:
  1367. return 8;
  1368. case TerrainTile::water:
  1369. return 25;
  1370. case TerrainTile::rock:
  1371. return 15;
  1372. default:
  1373. return -1;
  1374. }
  1375. }
  1376. UpgradeInfo CGameState::getUpgradeInfo(CArmedInstance *obj, int stackPos)
  1377. {
  1378. UpgradeInfo ret;
  1379. CCreature *base = &VLC->creh->creatures[obj->army.slots[stackPos].first];
  1380. if((obj->ID == TOWNI_TYPE) || ((obj->ID == HEROI_TYPE) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
  1381. {
  1382. CGTownInstance * t;
  1383. if(obj->ID == TOWNI_TYPE)
  1384. t = static_cast<CGTownInstance *>(const_cast<CArmedInstance *>(obj));
  1385. else
  1386. t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
  1387. for(std::set<si32>::iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++)
  1388. {
  1389. if( (*i) >= 37 && (*i) < 44 ) //upgraded creature dwelling
  1390. {
  1391. int nid = t->town->upgradedCreatures[(*i)-37]; //upgrade offered by that building
  1392. if(base->upgrades.find(nid) != base->upgrades.end()) //possible upgrade
  1393. {
  1394. ret.newID.push_back(nid);
  1395. ret.cost.push_back(std::set<std::pair<int,int> >());
  1396. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1397. {
  1398. int dif = VLC->creh->creatures[nid].cost[j] - base->cost[j];
  1399. if(dif)
  1400. ret.cost[ret.cost.size()-1].insert(std::make_pair(j,dif));
  1401. }
  1402. }
  1403. }
  1404. }//end for
  1405. }
  1406. //TODO: check if hero ability makes some upgrades possible
  1407. if(ret.newID.size())
  1408. ret.oldID = base->idNumber;
  1409. return ret;
  1410. }
  1411. float CGameState::getMarketEfficiency( int player, int mode/*=0*/ )
  1412. {
  1413. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1414. if(mode) return -1; //todo - support other modes
  1415. int mcount = 0;
  1416. for(unsigned int i=0;i<getPlayer(player)->towns.size();i++)
  1417. if(vstd::contains(getPlayer(player)->towns[i]->builtBuildings,14))
  1418. mcount++;
  1419. float ret = std::min(((float)mcount+1.0f)/20.0f,0.5f);
  1420. return ret;
  1421. }
  1422. void CGameState::loadTownDInfos()
  1423. {
  1424. for(int i=0;i<F_NUMBER;i++)
  1425. {
  1426. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1427. forts[i] = VLC->dobjinfo->castles[i];
  1428. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1429. }
  1430. }
  1431. void CGameState::getNeighbours(int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand)
  1432. {
  1433. int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1434. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1435. vec.clear();
  1436. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1437. {
  1438. int3 hlp = tile + dirs[i];
  1439. if(!map->isInTheMap(hlp))
  1440. continue;
  1441. if((indeterminate(onLand) || onLand == (map->getTile(hlp).tertype!=8) )
  1442. && map->getTile(hlp).tertype!=9)
  1443. {
  1444. vec.push_back(hlp);
  1445. }
  1446. }
  1447. }
  1448. int CGameState::getMovementCost(const CGHeroInstance *h, int3 src, int3 dest, int remainingMovePoints, bool checkLast)
  1449. {
  1450. if(src == dest) //same tile
  1451. return 0;
  1452. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1453. &d = map->terrain[dest.x][dest.y][dest.z];
  1454. //get basic cost
  1455. int ret = h->getTileCost(d,s);
  1456. if(src.x!=dest.x && src.y!=dest.y) //it's diagonal move
  1457. {
  1458. int old = ret;
  1459. ret *= 1.414;
  1460. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1461. if(ret > remainingMovePoints && remainingMovePoints > old)
  1462. {
  1463. return remainingMovePoints;
  1464. }
  1465. }
  1466. int left = remainingMovePoints-ret;
  1467. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1468. {
  1469. std::vector<int3> vec;
  1470. getNeighbours(dest, vec, s.tertype != TerrainTile::water);
  1471. for(size_t i=0; i < vec.size(); i++)
  1472. {
  1473. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1474. if(fcost <= left)
  1475. {
  1476. return ret;
  1477. }
  1478. }
  1479. ret = remainingMovePoints;
  1480. }
  1481. return ret;
  1482. }
  1483. int CGameState::canBuildStructure( const CGTownInstance *t, int ID )
  1484. {
  1485. int ret = 7; //allowed by default
  1486. //checking resources
  1487. CBuilding * pom = VLC->buildh->buildings[t->subID][ID];
  1488. if(!pom)return 8;
  1489. if(pom->Name().size()==0||pom->resources.size()==0)return 2;//TODO: why does this happen?
  1490. for(int res=0;res<pom->resources.size();res++) //TODO: support custom amount of resources
  1491. {
  1492. if(pom->resources[res] > getPlayer(t->tempOwner)->resources[res])
  1493. ret = 6; //lack of res
  1494. }
  1495. //checking for requirements
  1496. for( std::set<int>::iterator ri = VLC->townh->requirements[t->subID][ID].begin();
  1497. ri != VLC->townh->requirements[t->subID][ID].end();
  1498. ri++ )
  1499. {
  1500. if(t->builtBuildings.find(*ri)==t->builtBuildings.end())
  1501. ret = 8; //lack of requirements - cannot build
  1502. }
  1503. //can we build it?
  1504. if(t->forbiddenBuildings.find(ID)!=t->forbiddenBuildings.end())
  1505. ret = 2; //forbidden
  1506. else if(t->builded >= MAX_BUILDING_PER_TURN)
  1507. ret = 5; //building limit
  1508. if(ID == 13) //capitol
  1509. {
  1510. for(unsigned int in = 0; in < map->towns.size(); in++)
  1511. {
  1512. if(map->towns[in]->tempOwner==t->tempOwner && vstd::contains(map->towns[in]->builtBuildings,13))
  1513. {
  1514. ret = 0; //no more than one capitol
  1515. break;
  1516. }
  1517. }
  1518. }
  1519. else if(ID == 6) //shipyard
  1520. {
  1521. int3 t1(t->pos + int3(-1,3,0)),
  1522. t2(t->pos + int3(-3,3,0));
  1523. if(map->isInTheMap(t1) && map->getTile(t1).tertype != TerrainTile::water
  1524. && (map->isInTheMap(t2) && map->getTile(t2).tertype != TerrainTile::water))
  1525. ret = 1; //lack of water
  1526. }
  1527. if(t->builtBuildings.find(ID)!=t->builtBuildings.end()) //already built
  1528. ret = 4;
  1529. return ret;
  1530. }
  1531. void CGameState::apply(CPack *pack)
  1532. {
  1533. ui16 typ = typeList.getTypeID(pack);
  1534. assert(typ >= 0);
  1535. applierGs->apps[typ]->applyOnGS(this,pack);
  1536. }
  1537. PlayerState * CGameState::getPlayer( ui8 color )
  1538. {
  1539. if(vstd::contains(players,color))
  1540. {
  1541. return &players[color];
  1542. }
  1543. else
  1544. {
  1545. tlog2 << "Warning: Cannot find info for player " << int(color) << std::endl;
  1546. return NULL;
  1547. }
  1548. }
  1549. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1550. {
  1551. if(!map->isInTheMap(src) || !map->isInTheMap(dest)) //check input
  1552. return false;
  1553. int3 hpos = hero->getPosition(false);
  1554. tribool blockLandSea; //true - blocks sea, false - blocks land, indeterminate - allows all
  1555. if (!hero->canWalkOnSea())
  1556. blockLandSea = (map->getTile(hpos).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1557. else
  1558. blockLandSea = boost::logic::indeterminate;
  1559. //graph initialization
  1560. std::vector< std::vector<CPathNode> > graph;
  1561. graph.resize(map->width);
  1562. for(size_t i=0; i<graph.size(); ++i)
  1563. {
  1564. graph[i].resize(map->height);
  1565. for(size_t j=0; j<graph[i].size(); ++j)
  1566. {
  1567. const TerrainTile *tinfo = &map->terrain[i][j][src.z];
  1568. CPathNode &node = graph[i][j];
  1569. node.accesible = !tinfo->blocked;
  1570. node.dist = -1;
  1571. node.theNodeBefore = NULL;
  1572. node.visited = false;
  1573. node.coord.x = i;
  1574. node.coord.y = j;
  1575. node.coord.z = dest.z;
  1576. if ((tinfo->tertype == TerrainTile::rock) //it's rock
  1577. || ((blockLandSea) && (tinfo->tertype == TerrainTile::water)) //it's sea and we cannot walk on sea
  1578. || ((!blockLandSea) && (tinfo->tertype != TerrainTile::water)) //it's land and we cannot walk on land
  1579. || !getPlayer(hero->tempOwner)->fogOfWarMap[i][j][src.z] //tile is covered by the FoW
  1580. )
  1581. {
  1582. node.accesible = false;
  1583. }
  1584. }
  1585. }
  1586. //Special rules for the destination tile
  1587. {
  1588. const TerrainTile *t = &map->terrain[dest.x][dest.y][dest.z];
  1589. CPathNode &d = graph[dest.x][dest.y];
  1590. //tile may be blocked by blockvis / normal vis obj but it still must be accessible
  1591. if(t->visitable)
  1592. {
  1593. d.accesible = true; //for allowing visiting objects
  1594. }
  1595. if(blockLandSea && t->tertype == TerrainTile::water) //hero can walk only on land and dst lays on the water
  1596. {
  1597. size_t i = 0;
  1598. for(; i < t->visitableObjects.size(); i++)
  1599. if(t->visitableObjects[i]->ID == 8) //it's a Boat
  1600. break;
  1601. d.accesible = (i < t->visitableObjects.size()); //dest is accessible only if there is boat
  1602. }
  1603. else if(!blockLandSea && t->tertype != TerrainTile::water) //hero is moving by water
  1604. {
  1605. d.accesible = (t->siodmyTajemniczyBajt & 64) && !t->blocked; //tile is accessible if it's coastal and not blocked
  1606. }
  1607. }
  1608. //graph initialized
  1609. //initial tile - set cost on 0 and add to the queue
  1610. graph[src.x][src.y].dist = 0;
  1611. std::queue<CPathNode> mq;
  1612. mq.push(graph[src.x][src.y]);
  1613. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1614. std::vector<int3> neighbours;
  1615. neighbours.reserve(8);
  1616. while(!mq.empty())
  1617. {
  1618. CPathNode &cp = graph[mq.front().coord.x][mq.front().coord.y];
  1619. mq.pop();
  1620. if (cp.coord == dest) //it's destination tile
  1621. {
  1622. if (cp.dist < curDist) //that path is better than previous one
  1623. curDist = cp.dist;
  1624. continue;
  1625. }
  1626. else
  1627. {
  1628. if (cp.dist > curDist) //it's not dest and current length is greater than cost of already found path
  1629. continue;
  1630. }
  1631. //add accessible neighbouring nodes to the queue
  1632. getNeighbours(cp.coord, neighbours, boost::logic::indeterminate);
  1633. for(unsigned int i=0; i < neighbours.size(); i++)
  1634. {
  1635. CPathNode & dp = graph[neighbours[i].x][neighbours[i].y];
  1636. if(dp.accesible)
  1637. {
  1638. int cost = getMovementCost(hero,cp.coord,dp.coord,hero->movement - cp.dist);
  1639. if((dp.dist==-1 || (dp.dist > cp.dist + cost)) && dp.accesible && checkForVisitableDir(cp.coord, dp.coord) && checkForVisitableDir(dp.coord, cp.coord))
  1640. {
  1641. dp.dist = cp.dist + cost;
  1642. dp.theNodeBefore = &cp;
  1643. mq.push(dp);
  1644. }
  1645. }
  1646. }
  1647. }
  1648. CPathNode *curNode = &graph[dest.x][dest.y];
  1649. if(!curNode->theNodeBefore) //destination is not accessible
  1650. return false;
  1651. //fill ret with found path
  1652. ret.nodes.clear();
  1653. while(curNode->coord != graph[src.x][src.y].coord)
  1654. {
  1655. ret.nodes.push_back(*curNode);
  1656. curNode = curNode->theNodeBefore;
  1657. }
  1658. ret.nodes.push_back(graph[src.x][src.y]);
  1659. return true;
  1660. }
  1661. bool CGameState::isVisible(int3 pos, int player)
  1662. {
  1663. if(player == 255) //neutral player
  1664. return false;
  1665. return players[player].fogOfWarMap[pos.x][pos.y][pos.z];
  1666. }
  1667. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  1668. {
  1669. if(player == 255) //neutral player
  1670. return false;
  1671. //object is visible when at least one blocked tile is visible
  1672. for(int fx=0; fx<8; ++fx)
  1673. {
  1674. for(int fy=0; fy<6; ++fy)
  1675. {
  1676. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  1677. if(map->isInTheMap(pos)
  1678. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  1679. && isVisible(pos, player) )
  1680. return true;
  1681. }
  1682. }
  1683. return false;
  1684. }
  1685. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1686. {
  1687. const TerrainTile * pom = &map->getTile(dst);
  1688. for(unsigned int b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  1689. {
  1690. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  1691. continue;
  1692. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  1693. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  1694. {
  1695. return false;
  1696. }
  1697. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  1698. {
  1699. return false;
  1700. }
  1701. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  1702. {
  1703. return false;
  1704. }
  1705. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  1706. {
  1707. return false;
  1708. }
  1709. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  1710. {
  1711. return false;
  1712. }
  1713. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  1714. {
  1715. return false;
  1716. }
  1717. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  1718. {
  1719. return false;
  1720. }
  1721. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  1722. {
  1723. return false;
  1724. }
  1725. }
  1726. return true;
  1727. }
  1728. int BattleInfo::calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting)
  1729. {
  1730. int attackDefenseBonus,
  1731. minDmg = attacker->creature->damageMin * attacker->amount,
  1732. maxDmg = attacker->creature->damageMax * attacker->amount;
  1733. if(attacker->hasFeatureOfType(StackFeature::SIEGE_WEAPON)) //any siege weapon, but only ballista can attack
  1734. { //minDmg and maxDmg are multiplied by hero attack + 1
  1735. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  1736. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  1737. }
  1738. if(attacker->hasFeatureOfType(StackFeature::GENERAL_ATTACK_REDUCTION))
  1739. {
  1740. attackDefenseBonus = attacker->Attack() * (attacker->valOfFeatures(StackFeature::GENERAL_ATTACK_REDUCTION, -1024) / 100.0f) - defender->Defense();
  1741. }
  1742. else
  1743. {
  1744. attackDefenseBonus = attacker->Attack() - defender->Defense();
  1745. }
  1746. //calculating total attack/defense skills modifier
  1747. if(!shooting && attacker->hasFeatureOfType(StackFeature::ATTACK_BONUS, 0)) //bloodlust handling (etc.)
  1748. {
  1749. attackDefenseBonus += attacker->valOfFeatures(StackFeature::ATTACK_BONUS, 0);
  1750. }
  1751. if(shooting && attacker->hasFeatureOfType(StackFeature::ATTACK_BONUS, 1)) //precision handling (etc.)
  1752. {
  1753. attackDefenseBonus += attacker->valOfFeatures(StackFeature::ATTACK_BONUS, 1);
  1754. }
  1755. if(attacker->getEffect(55)) //slayer handling
  1756. {
  1757. std::vector<int> affectedIds;
  1758. switch(attacker->getEffect(55)->level)
  1759. {
  1760. case 3: //expert
  1761. {
  1762. affectedIds.push_back(40); //giant
  1763. affectedIds.push_back(41); //titan
  1764. affectedIds.push_back(152); //lord of thunder
  1765. } //continue adding ...
  1766. case 2: //advanced
  1767. {
  1768. affectedIds.push_back(12); //angel
  1769. affectedIds.push_back(13); //archangel
  1770. affectedIds.push_back(54); //devil
  1771. affectedIds.push_back(55); //arch devil
  1772. affectedIds.push_back(150); //supreme archangel
  1773. affectedIds.push_back(153); //antichrist
  1774. } //continue adding ...
  1775. case 0: case 1: //none and basic
  1776. {
  1777. affectedIds.push_back(26); //green dragon
  1778. affectedIds.push_back(27); //gold dragon
  1779. affectedIds.push_back(82); //red dragon
  1780. affectedIds.push_back(83); //black dragon
  1781. affectedIds.push_back(96); //behemot
  1782. affectedIds.push_back(97); //ancient behemot
  1783. affectedIds.push_back(110); //hydra
  1784. affectedIds.push_back(111); //chaos hydra
  1785. affectedIds.push_back(132); //azure dragon
  1786. affectedIds.push_back(133); //crystal dragon
  1787. affectedIds.push_back(134); //faerie dragon
  1788. affectedIds.push_back(135); //rust dragon
  1789. affectedIds.push_back(151); //diamond dragon
  1790. affectedIds.push_back(154); //blood dragon
  1791. affectedIds.push_back(155); //darkness dragon
  1792. affectedIds.push_back(156); //ghost behemot
  1793. affectedIds.push_back(157); //hell hydra
  1794. break;
  1795. }
  1796. }
  1797. for(unsigned int g=0; g<affectedIds.size(); ++g)
  1798. {
  1799. if(defender->creature->idNumber == affectedIds[g])
  1800. {
  1801. attackDefenseBonus += VLC->spellh->spells[55].powers[attacker->getEffect(55)->level];
  1802. break;
  1803. }
  1804. }
  1805. }
  1806. float dmgBonusMultiplier = 1.0f;
  1807. //bonus from attack/defense skills
  1808. if(attackDefenseBonus < 0) //decreasing dmg
  1809. {
  1810. if(0.02f * (-attackDefenseBonus) > 0.3f)
  1811. {
  1812. dmgBonusMultiplier += -0.3f;
  1813. }
  1814. else
  1815. {
  1816. dmgBonusMultiplier += 0.02f * attackDefenseBonus;
  1817. }
  1818. }
  1819. else //increasing dmg
  1820. {
  1821. if(0.05f * attackDefenseBonus > 4.0f)
  1822. {
  1823. dmgBonusMultiplier += 4.0f;
  1824. }
  1825. else
  1826. {
  1827. dmgBonusMultiplier += 0.05f * attackDefenseBonus;
  1828. }
  1829. }
  1830. //handling secondary abilities and artifacts giving premies to them
  1831. if(attackerHero)
  1832. {
  1833. if(shooting)
  1834. {
  1835. switch(attackerHero->getSecSkillLevel(1)) //archery
  1836. {
  1837. case 1: //basic
  1838. dmgBonusMultiplier *= 1.1f;
  1839. break;
  1840. case 2: //advanced
  1841. dmgBonusMultiplier *= 1.25f;
  1842. break;
  1843. case 3: //expert
  1844. dmgBonusMultiplier *= 1.5f;
  1845. break;
  1846. }
  1847. if(attackerHero->getSecSkillLevel(1) > 0) //non-none level
  1848. {
  1849. //apply artifact premy to archery
  1850. dmgBonusMultiplier *= (100.0f + attackerHero->valOfBonuses(HeroBonus::SECONDARY_SKILL_PREMY, 1)) / 100.0f;
  1851. }
  1852. }
  1853. else
  1854. {
  1855. switch(attackerHero->getSecSkillLevel(22)) //offense
  1856. {
  1857. case 1: //basic
  1858. dmgBonusMultiplier *= 1.1f;
  1859. break;
  1860. case 2: //advanced
  1861. dmgBonusMultiplier *= 1.2f;
  1862. break;
  1863. case 3: //expert
  1864. dmgBonusMultiplier *= 1.3f;
  1865. break;
  1866. }
  1867. }
  1868. }
  1869. if(defendingHero)
  1870. {
  1871. switch(defendingHero->getSecSkillLevel(23)) //armorer
  1872. {
  1873. case 1: //basic
  1874. dmgBonusMultiplier *= 0.95f;
  1875. break;
  1876. case 2: //advanced
  1877. dmgBonusMultiplier *= 0.9f;
  1878. break;
  1879. case 3: //expert
  1880. dmgBonusMultiplier *= 0.85f;
  1881. break;
  1882. }
  1883. }
  1884. //handling spell effects
  1885. if(!shooting && defender->hasFeatureOfType(StackFeature::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  1886. {
  1887. dmgBonusMultiplier *= float(defender->valOfFeatures(StackFeature::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0f;
  1888. }
  1889. else if(shooting && defender->hasFeatureOfType(StackFeature::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  1890. {
  1891. dmgBonusMultiplier *= float(defender->valOfFeatures(StackFeature::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0f;
  1892. }
  1893. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  1894. {
  1895. dmgBonusMultiplier *= 0.8f * float(VLC->spellh->spells[42].powers[attacker->getEffect(42)->level]); //the second factor is 1 or 0
  1896. }
  1897. minDmg *= dmgBonusMultiplier;
  1898. maxDmg *= dmgBonusMultiplier;
  1899. if(attacker->getEffect(42)) //curse handling (rest)
  1900. {
  1901. minDmg -= VLC->spellh->spells[42].powers[attacker->getEffect(42)->level];
  1902. return minDmg;
  1903. }
  1904. else if(attacker->getEffect(41)) //bless handling
  1905. {
  1906. maxDmg += VLC->spellh->spells[41].powers[attacker->getEffect(41)->level];
  1907. return maxDmg;
  1908. }
  1909. else
  1910. {
  1911. if(minDmg != maxDmg)
  1912. return minDmg + rand() % (maxDmg - minDmg + 1);
  1913. else
  1914. return minDmg;
  1915. }
  1916. tlog1 << "We are too far in calculateDmg...\n";
  1917. return -1;
  1918. }
  1919. void BattleInfo::calculateCasualties( std::set<std::pair<ui32,si32> > *casualties )
  1920. {
  1921. for(unsigned int i=0; i<stacks.size();i++)//setting casualties
  1922. {
  1923. if(!stacks[i]->alive())
  1924. {
  1925. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount));
  1926. }
  1927. else if(stacks[i]->amount != stacks[i]->baseAmount)
  1928. {
  1929. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount - stacks[i]->amount));
  1930. }
  1931. }
  1932. }
  1933. si8 CGameState::battleMaxSpellLevel()
  1934. {
  1935. if(!curB) //there is not battle
  1936. {
  1937. tlog1 << "si8 CGameState::maxSpellLevel() call when there is no battle!" << std::endl;
  1938. throw "si8 CGameState::maxSpellLevel() call when there is no battle!";
  1939. }
  1940. si8 levelLimit = SPELL_LEVELS;
  1941. const CGHeroInstance *h1 = getHero(curB->hero1);
  1942. if(h1)
  1943. {
  1944. for(std::list<HeroBonus>::const_iterator i = h1->bonuses.begin(); i != h1->bonuses.end(); i++)
  1945. if(i->type == HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL)
  1946. amin(levelLimit, i->val);
  1947. }
  1948. const CGHeroInstance *h2 = getHero(curB->hero2);
  1949. if(h2)
  1950. {
  1951. for(std::list<HeroBonus>::const_iterator i = h2->bonuses.begin(); i != h2->bonuses.end(); i++)
  1952. if(i->type == HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL)
  1953. amin(levelLimit, i->val);
  1954. }
  1955. return levelLimit;
  1956. }
  1957. std::set<CStack*> BattleInfo::getAttackedCreatures(const CSpell * s, const CGHeroInstance * caster, int destinationTile)
  1958. {
  1959. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, caster->getSpellSchoolLevel(s));
  1960. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurences of two hex creatures*/
  1961. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  1962. if(s->id == 24 || s->id == 25 || s->id == 26) //death ripple, destroy undead and armageddon
  1963. {
  1964. for(int it=0; it<stacks.size(); ++it)
  1965. {
  1966. if((s->id == 24 && !stacks[it]->creature->isUndead()) //death ripple
  1967. || (s->id == 25 && stacks[it]->creature->isUndead()) //destroy undead
  1968. || (s->id == 26) //armageddon
  1969. )
  1970. {
  1971. attackedCres.insert(stacks[it]);
  1972. }
  1973. }
  1974. }
  1975. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_1") != std::string::npos
  1976. || 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
  1977. {
  1978. if(caster->getSpellSchoolLevel(s) < 3) /*not expert */
  1979. {
  1980. CStack * st = getStackT(destinationTile, onlyAlive);
  1981. if(st)
  1982. attackedCres.insert(st);
  1983. }
  1984. else
  1985. {
  1986. for(int it=0; it<stacks.size(); ++it)
  1987. {
  1988. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  1989. if((VLC->spellh->spells[s->id].positiveness >= 0 && stacks[it]->owner == caster->tempOwner)
  1990. ||(VLC->spellh->spells[s->id].positiveness <= 0 && stacks[it]->owner != caster->tempOwner )
  1991. )
  1992. {
  1993. if(!onlyAlive || stacks[it]->alive())
  1994. attackedCres.insert(stacks[it]);
  1995. }
  1996. }
  1997. } //if(caster->getSpellSchoolLevel(s) < 3)
  1998. }
  1999. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET") != std::string::npos) //spell to be cast on one specific creature
  2000. {
  2001. CStack * st = getStackT(destinationTile, onlyAlive);
  2002. if(st)
  2003. attackedCres.insert(st);
  2004. }
  2005. else //custom range from attackedHexes
  2006. {
  2007. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  2008. {
  2009. CStack * st = getStackT(*it, onlyAlive);
  2010. if(st)
  2011. attackedCres.insert(st);
  2012. }
  2013. }
  2014. return attackedCres;
  2015. }
  2016. int BattleInfo::calculateSpellDuration(const CSpell * spell, const CGHeroInstance * caster)
  2017. {
  2018. switch(spell->id)
  2019. {
  2020. case 56: //frenzy
  2021. return 1;
  2022. default: //other spells
  2023. return caster->getPrimSkillLevel(2) + caster->valOfBonuses(HeroBonus::SPELL_DURATION);
  2024. }
  2025. }
  2026. CStack * BattleInfo::generateNewStack(const CGHeroInstance * owner, int creatureID, int amount, int stackID, bool attackerOwned, int slot, int /*TerrainTile::EterrainType*/ terrain, int position)
  2027. {
  2028. CStack * ret = new CStack(&VLC->creh->creatures[creatureID], amount, owner ? owner->tempOwner : 255, stackID, attackerOwned, slot);
  2029. if(owner)
  2030. {
  2031. ret->features.push_back(makeFeature(StackFeature::SPEED_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->valOfBonuses(HeroBonus::STACKS_SPEED), StackFeature::BONUS_FROM_HERO));
  2032. //base luck/morale calculations
  2033. ret->morale = owner->getCurrentMorale(slot, false);
  2034. ret->luck = owner->getCurrentLuck(slot, false);
  2035. //other bonuses
  2036. ret->features.push_back(makeFeature(StackFeature::ATTACK_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->getPrimSkillLevel(0), StackFeature::BONUS_FROM_HERO));
  2037. ret->features.push_back(makeFeature(StackFeature::DEFENCE_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->getPrimSkillLevel(1), StackFeature::BONUS_FROM_HERO));
  2038. ret->features.push_back(makeFeature(StackFeature::HP_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->valOfBonuses(HeroBonus::STACK_HEALTH), StackFeature::BONUS_FROM_HERO));
  2039. ret->firstHPleft = ret->MaxHealth();
  2040. }
  2041. else
  2042. {
  2043. ret->morale = 0;
  2044. ret->luck = 0;
  2045. }
  2046. //native terrain bonuses
  2047. int faction = ret->creature->faction;
  2048. if(faction >= 0 && VLC->heroh->nativeTerrains[faction] == terrain)
  2049. {
  2050. ret->features.push_back(makeFeature(StackFeature::SPEED_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2051. ret->features.push_back(makeFeature(StackFeature::ATTACK_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2052. ret->features.push_back(makeFeature(StackFeature::DEFENCE_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2053. }
  2054. ret->position = position;
  2055. return ret;
  2056. }
  2057. CStack * BattleInfo::getNextStack()
  2058. {
  2059. CStack *current = getStack(activeStack);
  2060. for (unsigned int i = 0; i < stacks.size(); i++) //find fastest not moved/waited stack (stacks vector is sorted by speed)
  2061. {
  2062. if(stacks[i]->willMove() && !vstd::contains(stacks[i]->state,WAITING))
  2063. return stacks[i];
  2064. }
  2065. for (int i = stacks.size() - 1; i >= 0 ; i--) //find slowest waiting stack
  2066. {
  2067. if(stacks[i]->willMove())
  2068. return stacks[i];
  2069. }
  2070. return NULL; //all stacks moved or defending!
  2071. }
  2072. std::vector<CStack> BattleInfo::getStackQueue()
  2073. {
  2074. std::vector<CStack> ret;
  2075. std::vector<int> taken; //if non-zero value, corresponding stack has been placed in ret
  2076. taken.resize(stacks.size());
  2077. for(unsigned int g=0; g<taken.size(); ++g)
  2078. {
  2079. taken[g] = 0;
  2080. }
  2081. for(int moved=0; moved<2; ++moved) //in first cycle we add stacks that can act in current turn, in second one the rest of them
  2082. {
  2083. for(unsigned int gc=0; gc<stacks.size(); ++gc)
  2084. {
  2085. int id = -1, speed = -1;
  2086. for(unsigned int i=0; i<stacks.size(); ++i) //find not waited stacks only
  2087. {
  2088. if((moved == 1 ||!vstd::contains(stacks[i]->state, DEFENDING))
  2089. && stacks[i]->alive()
  2090. && (moved == 1 || !vstd::contains(stacks[i]->state, MOVED))
  2091. && !vstd::contains(stacks[i]->state,WAITING)
  2092. && taken[i]==0
  2093. && !stacks[i]->hasFeatureOfType(StackFeature::NOT_ACTIVE)) //eg. Ammo Cart
  2094. {
  2095. if(speed == -1 || stacks[i]->Speed() > speed)
  2096. {
  2097. id = i;
  2098. speed = stacks[i]->Speed();
  2099. }
  2100. }
  2101. }
  2102. if(id != -1)
  2103. {
  2104. ret.push_back(*stacks[id]);
  2105. taken[id] = 1;
  2106. }
  2107. else //choose something from not moved stacks
  2108. {
  2109. int id = -1, speed = 10000; //infinite speed
  2110. for(unsigned int i=0; i<stacks.size(); ++i) //find waited stacks only
  2111. {
  2112. if((moved == 1 ||!vstd::contains(stacks[i]->state, DEFENDING))
  2113. && stacks[i]->alive()
  2114. && (moved == 1 || !vstd::contains(stacks[i]->state, MOVED))
  2115. && vstd::contains(stacks[i]->state,WAITING)
  2116. && taken[i]==0
  2117. && !stacks[i]->hasFeatureOfType(StackFeature::NOT_ACTIVE)) //eg. Ammo Cart
  2118. {
  2119. if(stacks[i]->Speed() < speed) //slowest one
  2120. {
  2121. id = i;
  2122. speed = stacks[i]->Speed();
  2123. }
  2124. }
  2125. }
  2126. if(id != -1)
  2127. {
  2128. ret.push_back(*stacks[id]);
  2129. taken[id] = 1;
  2130. }
  2131. else
  2132. {
  2133. break; //no stacks have been found, so none of them will be found in next iterations
  2134. }
  2135. }
  2136. }
  2137. }
  2138. return ret;
  2139. }
  2140. int3 CPath::startPos() const
  2141. {
  2142. return nodes[nodes.size()-1].coord;
  2143. }
  2144. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  2145. {
  2146. if (mode==0)
  2147. {
  2148. for (unsigned int i=0;i<nodes.size();i++)
  2149. {
  2150. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2151. }
  2152. }
  2153. }
  2154. int3 CPath::endPos() const
  2155. {
  2156. return nodes[0].coord;
  2157. }