CGameState.cpp 62 KB

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