CGameState.cpp 55 KB

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