CGameState.cpp 53 KB

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