CGameState.cpp 52 KB

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