CGameState.cpp 55 KB

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