CGameState.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874
  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 115:
  566. {
  567. GiveBonus *rh = static_cast<GiveBonus*>(pack);
  568. CGHeroInstance *h = getHero(rh->hid);
  569. h->bonuses.push_back(CGHeroInstance::Bonus(rh->bduration,rh->btype,rh->bval,rh->bid,toString(rh->bdescr)));
  570. break;
  571. }
  572. case 500:
  573. {
  574. RemoveObject *rh = static_cast<RemoveObject*>(pack);
  575. CGObjectInstance *obj = map->objects[rh->id];
  576. if(obj->ID==34)
  577. {
  578. CGHeroInstance *h = static_cast<CGHeroInstance*>(obj);
  579. std::vector<CGHeroInstance*>::iterator nitr = std::find(map->heroes.begin(), map->heroes.end(),h);
  580. map->heroes.erase(nitr);
  581. int player = h->tempOwner;
  582. nitr = std::find(players[player].heroes.begin(), players[player].heroes.end(), h);
  583. players[player].heroes.erase(nitr);
  584. if(h->visitedTown)
  585. {
  586. if(h->inTownGarrison)
  587. h->visitedTown->garrisonHero = NULL;
  588. else
  589. h->visitedTown->visitingHero = NULL;
  590. h->visitedTown = NULL;
  591. }
  592. }
  593. map->objects[rh->id] = NULL;
  594. //unblock tiles
  595. if(obj->defInfo)
  596. {
  597. map->removeBlockVisTiles(obj);
  598. }
  599. break;
  600. }
  601. case 501://hero try-move
  602. {
  603. TryMoveHero * n = static_cast<TryMoveHero*>(pack);
  604. CGHeroInstance *h = static_cast<CGHeroInstance*>(map->objects[n->id]);
  605. h->movement = n->movePoints;
  606. if(n->start!=n->end && n->result)
  607. {
  608. map->removeBlockVisTiles(h);
  609. h->pos = n->end;
  610. map->addBlockVisTiles(h);
  611. }
  612. BOOST_FOREACH(int3 t, n->fowRevealed)
  613. players[h->getOwner()].fogOfWarMap[t.x][t.y][t.z] = 1;
  614. break;
  615. }
  616. case 502:
  617. {
  618. SetGarrisons * n = static_cast<SetGarrisons*>(pack);
  619. for(std::map<ui32,CCreatureSet>::iterator i = n->garrs.begin(); i!=n->garrs.end(); i++)
  620. {
  621. CArmedInstance *ai = static_cast<CArmedInstance*>(map->objects[i->first]);
  622. ai->army = i->second;
  623. if(ai->ID==98 && (static_cast<CGTownInstance*>(ai))->garrisonHero) //if there is a hero in garrison then we must update also his army
  624. const_cast<CGHeroInstance*>((static_cast<CGTownInstance*>(ai))->garrisonHero)->army = i->second;
  625. else if(ai->ID==34)
  626. {
  627. CGHeroInstance *h = static_cast<CGHeroInstance*>(ai);
  628. if(h->visitedTown && h->inTownGarrison)
  629. h->visitedTown->army = i->second;
  630. }
  631. }
  632. break;
  633. }
  634. case 503:
  635. {
  636. //SetStrInfo *ssi = static_cast<SetStrInfo*>(pack);
  637. //static_cast<CGTownInstance*>(map->objects[ssi->tid])->strInfo.creatures = ssi->cres;
  638. break;
  639. }
  640. case 504:
  641. {
  642. NewStructures *ns = static_cast<NewStructures*>(pack);
  643. CGTownInstance*t = static_cast<CGTownInstance*>(map->objects[ns->tid]);
  644. BOOST_FOREACH(si32 bid,ns->bid)
  645. t->builtBuildings.insert(bid);
  646. t->builded = ns->builded;
  647. break;
  648. }
  649. case 506:
  650. {
  651. SetAvailableCreatures *sac = static_cast<SetAvailableCreatures*>(pack);
  652. static_cast<CGTownInstance*>(map->objects[sac->tid])->strInfo.creatures = sac->creatures;
  653. break;
  654. }
  655. case 508:
  656. {
  657. SetHeroesInTown *sac = static_cast<SetHeroesInTown*>(pack);
  658. CGTownInstance *t = getTown(sac->tid);
  659. CGHeroInstance *v = getHero(sac->visiting), *g = getHero(sac->garrison);
  660. t->visitingHero = v;
  661. t->garrisonHero = g;
  662. if(v)
  663. {
  664. v->visitedTown = t;
  665. v->inTownGarrison = false;
  666. map->addBlockVisTiles(v);
  667. }
  668. if(g)
  669. {
  670. g->visitedTown = t;
  671. g->inTownGarrison = true;
  672. map->removeBlockVisTiles(g);
  673. }
  674. break;
  675. }
  676. case 509:
  677. {
  678. SetHeroArtifacts *sha = static_cast<SetHeroArtifacts*>(pack);
  679. CGHeroInstance *h = getHero(sha->hid);
  680. h->artifacts = sha->artifacts;
  681. h->artifWorn = sha->artifWorn;
  682. break;
  683. }
  684. case 514:
  685. {
  686. SetSelection *ss = static_cast<SetSelection*>(pack);
  687. players[ss->player].currentSelection = ss->id;
  688. break;
  689. }
  690. case 515:
  691. {
  692. HeroRecruited *sha = static_cast<HeroRecruited*>(pack);
  693. CGHeroInstance *h = hpool.heroesPool[sha->hid];
  694. CGTownInstance *t = getTown(sha->tid);
  695. h->setOwner(sha->player);
  696. h->pos = sha->tile;
  697. h->movement = h->maxMovePoints(true);
  698. hpool.heroesPool.erase(sha->hid);
  699. if(h->id < 0)
  700. {
  701. h->id = map->objects.size();
  702. map->objects.push_back(h);
  703. }
  704. else
  705. map->objects[h->id] = h;
  706. h->initHeroDefInfo();
  707. map->heroes.push_back(h);
  708. players[h->tempOwner].heroes.push_back(h);
  709. map->addBlockVisTiles(h);
  710. t->visitingHero = h;
  711. h->visitedTown = t;
  712. h->inTownGarrison = false;
  713. break;
  714. }
  715. case 1001://set object property
  716. {
  717. SetObjectProperty *p = static_cast<SetObjectProperty*>(pack);
  718. setObjProperty(p);
  719. break;
  720. }
  721. case 1002:
  722. {
  723. SetHoverName *shn = static_cast<SetHoverName*>(pack);
  724. map->objects[shn->id]->hoverName = toString(shn->name);
  725. break;
  726. }
  727. case 2000:
  728. {
  729. HeroLevelUp * bs = static_cast<HeroLevelUp*>(pack);
  730. getHero(bs->heroid)->level = bs->level;
  731. break;
  732. }
  733. case 3000:
  734. {
  735. BattleStart * bs = static_cast<BattleStart*>(pack);
  736. curB = bs->info;
  737. break;
  738. }
  739. case 3001:
  740. {
  741. BattleNextRound *ns = static_cast<BattleNextRound*>(pack);
  742. curB->round = ns->round;
  743. for(int i=0; i<curB->stacks.size();i++)
  744. {
  745. curB->stacks[i]->state -= DEFENDING;
  746. curB->stacks[i]->state -= WAITING;
  747. curB->stacks[i]->state -= MOVED;
  748. curB->stacks[i]->state -= HAD_MORALE;
  749. curB->stacks[i]->counterAttacks = 1;
  750. }
  751. break;
  752. }
  753. case 3002:
  754. {
  755. BattleSetActiveStack *ns = static_cast<BattleSetActiveStack*>(pack);
  756. curB->activeStack = ns->stack;
  757. break;
  758. }
  759. case 3003:
  760. {
  761. BattleResult *br = static_cast<BattleResult*>(pack);
  762. //TODO: give exp, artifacts to winner, decrease armies (casualties)
  763. for(unsigned i=0;i<curB->stacks.size();i++)
  764. delete curB->stacks[i];
  765. delete curB;
  766. curB = NULL;
  767. break;
  768. }
  769. case 3004:
  770. {
  771. BattleStackMoved *br = static_cast<BattleStackMoved*>(pack);
  772. curB->getStack(br->stack)->position = br->tile;
  773. break;
  774. }
  775. case 3005:
  776. {
  777. BattleStackAttacked *br = static_cast<BattleStackAttacked*>(pack);
  778. CStack * at = curB->getStack(br->stackAttacked);
  779. at->amount = br->newAmount;
  780. at->firstHPleft = br->newHP;
  781. if(br->killed())
  782. at->state -= ALIVE;
  783. break;
  784. }
  785. case 3006:
  786. {
  787. BattleAttack *br = static_cast<BattleAttack*>(pack);
  788. CStack *attacker = curB->getStack(br->stackAttacking);
  789. if(br->counter())
  790. attacker->counterAttacks--;
  791. if(br->shot())
  792. attacker->shots--;
  793. applyNL(&br->bsa);
  794. break;
  795. }
  796. case 3007:
  797. {
  798. StartAction *br = static_cast<StartAction*>(pack);
  799. CStack *st = curB->getStack(br->ba.stackNumber);
  800. switch(br->ba.actionType)
  801. {
  802. case 3:
  803. st->state.insert(DEFENDING);
  804. break;
  805. case 8:
  806. st->state.insert(WAITING);
  807. break;
  808. case 2: case 6: case 7: case 9: case 10:
  809. st->state.insert(MOVED);
  810. break;
  811. }
  812. break;
  813. }
  814. case 3009:
  815. {
  816. SpellCasted *sc = static_cast<SpellCasted*>(pack);
  817. CGHeroInstance *h = (sc->side) ? getHero(curB->hero2) : getHero(curB->hero1);
  818. if(h)
  819. h->mana -= VLC->spellh->spells[sc->id].costs[sc->skill];
  820. //TODO: counter
  821. break;
  822. }
  823. case 3010:
  824. {
  825. SetStackEffect *sc = static_cast<SetStackEffect*>(pack);
  826. CStack *stack = curB->getStack(sc->stack);
  827. stack->effects.push_back(sc->effect);
  828. break;
  829. }
  830. }
  831. }
  832. void CGameState::apply(IPack * pack)
  833. {
  834. while(!mx->try_lock())
  835. boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  836. applyNL(pack);
  837. mx->unlock();
  838. }
  839. int CGameState::pickHero(int owner)
  840. {
  841. int h=-1;
  842. if(!map->getHero(h = scenarioOps->getIthPlayersSettings(owner).hero,0) && h>=0) //we haven't used selected hero
  843. return h;
  844. int f = scenarioOps->getIthPlayersSettings(owner).castle;
  845. int i=0;
  846. do //try to find free hero of our faction
  847. {
  848. i++;
  849. h = scenarioOps->getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  850. } while( map->getHero(h) && i<175);
  851. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  852. {
  853. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  854. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  855. if(!map->getHero(j))
  856. h=j;
  857. }
  858. return h;
  859. }
  860. CGHeroInstance *CGameState::getHero(int objid)
  861. {
  862. if(objid<0 || objid>=map->objects.size())
  863. return NULL;
  864. return static_cast<CGHeroInstance *>(map->objects[objid]);
  865. }
  866. CGTownInstance *CGameState::getTown(int objid)
  867. {
  868. if(objid<0 || objid>=map->objects.size())
  869. return NULL;
  870. return static_cast<CGTownInstance *>(map->objects[objid]);
  871. }
  872. std::pair<int,int> CGameState::pickObject(CGObjectInstance *obj)
  873. {
  874. switch(obj->ID)
  875. {
  876. case 65: //random artifact
  877. return std::pair<int,int>(5,(ran()%136)+7); //tylko sensowny zakres - na poczatku sa katapulty itp, na koncu specjalne i blanki
  878. case 66: //random treasure artifact
  879. return std::pair<int,int>(5,VLC->arth->treasures[ran()%VLC->arth->treasures.size()]->id);
  880. case 67: //random minor artifact
  881. return std::pair<int,int>(5,VLC->arth->minors[ran()%VLC->arth->minors.size()]->id);
  882. case 68: //random major artifact
  883. return std::pair<int,int>(5,VLC->arth->majors[ran()%VLC->arth->majors.size()]->id);
  884. case 69: //random relic artifact
  885. return std::pair<int,int>(5,VLC->arth->relics[ran()%VLC->arth->relics.size()]->id);
  886. case 70: //random hero
  887. {
  888. return std::pair<int,int>(34,pickHero(obj->tempOwner));
  889. }
  890. case 71: //random monster
  891. {
  892. int r;
  893. do
  894. {
  895. r = ran()%197;
  896. } while (vstd::contains(VLC->creh->notUsedMonsters,r));
  897. return std::pair<int,int>(54,r);
  898. }
  899. case 72: //random monster lvl1
  900. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  901. case 73: //random monster lvl2
  902. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  903. case 74: //random monster lvl3
  904. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  905. case 75: //random monster lvl4
  906. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  907. case 76: //random resource
  908. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  909. case 77: //random town
  910. {
  911. int align = ((CGTownInstance*)obj)->alignment,
  912. f;
  913. if(align>PLAYER_LIMIT-1)//same as owner / random
  914. {
  915. if(obj->tempOwner > PLAYER_LIMIT-1)
  916. f = -1; //random
  917. else
  918. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  919. }
  920. else
  921. {
  922. f = scenarioOps->getIthPlayersSettings(align).castle;
  923. }
  924. if(f<0) f = ran()%VLC->townh->towns.size();
  925. return std::pair<int,int>(98,f);
  926. }
  927. case 162: //random monster lvl5
  928. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  929. case 163: //random monster lvl6
  930. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  931. case 164: //random monster lvl7
  932. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  933. case 216: //random dwelling
  934. {
  935. int faction = ran()%F_NUMBER;
  936. CCreGen2ObjInfo* info =(CCreGen2ObjInfo*)obj->info;
  937. if (info->asCastle)
  938. {
  939. for(int i=0;i<map->objects.size();i++)
  940. {
  941. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  942. {
  943. randomizeObject(map->objects[i]); //we have to randomize the castle first
  944. faction = map->objects[i]->subID;
  945. break;
  946. }
  947. else if(map->objects[i]->ID==98 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  948. {
  949. faction = map->objects[i]->subID;
  950. break;
  951. }
  952. }
  953. }
  954. else
  955. {
  956. while((!(info->castles[0]&(1<<faction))))
  957. {
  958. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  959. break;
  960. faction = ran()%F_NUMBER;
  961. }
  962. }
  963. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  964. int cid = VLC->townh->towns[faction].basicCreatures[level];
  965. for(int i=0;i<VLC->objh->cregens.size();i++)
  966. if(VLC->objh->cregens[i]==cid)
  967. return std::pair<int,int>(17,i);
  968. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  969. return std::pair<int,int>(17,0);
  970. }
  971. case 217:
  972. {
  973. int faction = ran()%F_NUMBER;
  974. CCreGenObjInfo* info =(CCreGenObjInfo*)obj->info;
  975. if (info->asCastle)
  976. {
  977. for(int i=0;i<map->objects.size();i++)
  978. {
  979. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  980. {
  981. randomizeObject(map->objects[i]); //we have to randomize the castle first
  982. faction = map->objects[i]->subID;
  983. break;
  984. }
  985. else if(map->objects[i]->ID==98 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  986. {
  987. faction = map->objects[i]->subID;
  988. break;
  989. }
  990. }
  991. }
  992. else
  993. {
  994. while((!(info->castles[0]&(1<<faction))))
  995. {
  996. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  997. break;
  998. faction = ran()%F_NUMBER;
  999. }
  1000. }
  1001. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  1002. for(int i=0;i<VLC->objh->cregens.size();i++)
  1003. if(VLC->objh->cregens[i]==cid)
  1004. return std::pair<int,int>(17,i);
  1005. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  1006. return std::pair<int,int>(17,0);
  1007. }
  1008. case 218:
  1009. {
  1010. CCreGen3ObjInfo* info =(CCreGen3ObjInfo*)obj->info;
  1011. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  1012. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  1013. for(int i=0;i<VLC->objh->cregens.size();i++)
  1014. if(VLC->objh->cregens[i]==cid)
  1015. return std::pair<int,int>(17,i);
  1016. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  1017. return std::pair<int,int>(17,0);
  1018. }
  1019. }
  1020. return std::pair<int,int>(-1,-1);
  1021. }
  1022. void CGameState::randomizeObject(CGObjectInstance *cur)
  1023. {
  1024. std::pair<int,int> ran = pickObject(cur);
  1025. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  1026. {
  1027. if(cur->ID==98) //town - set def
  1028. {
  1029. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  1030. if(t->hasCapitol())
  1031. t->defInfo = capitols[t->subID];
  1032. else if(t->hasFort())
  1033. t->defInfo = forts[t->subID];
  1034. else
  1035. t->defInfo = villages[t->subID];
  1036. }
  1037. return;
  1038. }
  1039. else if(ran.first==34)//special code for hero
  1040. {
  1041. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  1042. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  1043. cur->ID = ran.first;
  1044. h->portrait = cur->subID = ran.second;
  1045. h->type = VLC->heroh->heroes[ran.second];
  1046. map->heroes.push_back(h);
  1047. return; //TODO: maybe we should do something with definfo?
  1048. }
  1049. else if(ran.first==98)//special code for town
  1050. {
  1051. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  1052. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  1053. cur->ID = ran.first;
  1054. cur->subID = ran.second;
  1055. t->town = &VLC->townh->towns[ran.second];
  1056. if(t->hasCapitol())
  1057. t->defInfo = capitols[t->subID];
  1058. else if(t->hasFort())
  1059. t->defInfo = forts[t->subID];
  1060. else
  1061. t->defInfo = villages[t->subID];
  1062. map->towns.push_back(t);
  1063. return;
  1064. }
  1065. //we have to replace normal random object
  1066. cur->ID = ran.first;
  1067. cur->subID = ran.second;
  1068. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  1069. if(!cur->defInfo)
  1070. {
  1071. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  1072. return;
  1073. }
  1074. }
  1075. int CGameState::getDate(int mode) const
  1076. {
  1077. int temp;
  1078. switch (mode)
  1079. {
  1080. case 0:
  1081. return day;
  1082. break;
  1083. case 1:
  1084. temp = (day)%7;
  1085. if (temp)
  1086. return temp;
  1087. else return 7;
  1088. break;
  1089. case 2:
  1090. temp = ((day-1)/7)+1;
  1091. if (!(temp%4))
  1092. return 4;
  1093. else
  1094. return (temp%4);
  1095. break;
  1096. case 3:
  1097. return ((day-1)/28)+1;
  1098. break;
  1099. }
  1100. return 0;
  1101. }
  1102. CGameState::CGameState()
  1103. {
  1104. mx = new boost::shared_mutex();
  1105. map = NULL;
  1106. curB = NULL;
  1107. scenarioOps = NULL;
  1108. }
  1109. CGameState::~CGameState()
  1110. {
  1111. delete mx;
  1112. delete map;
  1113. delete curB;
  1114. delete scenarioOps;
  1115. }
  1116. void CGameState::init(StartInfo * si, Mapa * map, int Seed)
  1117. {
  1118. day = 0;
  1119. seed = Seed;
  1120. ran.seed((boost::int32_t)seed);
  1121. scenarioOps = si;
  1122. this->map = map;
  1123. loadTownDInfos();
  1124. //picking random factions for players
  1125. for(int i=0;i<scenarioOps->playerInfos.size();i++)
  1126. {
  1127. if(scenarioOps->playerInfos[i].castle==-1)
  1128. {
  1129. int f;
  1130. do
  1131. {
  1132. f = ran()%F_NUMBER;
  1133. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  1134. scenarioOps->playerInfos[i].castle = f;
  1135. }
  1136. }
  1137. //randomizing objects
  1138. for(int no=0; no<map->objects.size(); ++no)
  1139. {
  1140. randomizeObject(map->objects[no]);
  1141. if(map->objects[no]->ID==26)
  1142. {
  1143. map->objects[no]->defInfo->handler=NULL;
  1144. map->removeBlockVisTiles(map->objects[no]);
  1145. map->objects[no]->defInfo->blockMap[5] = 255;
  1146. map->addBlockVisTiles(map->objects[no]);
  1147. }
  1148. map->objects[no]->hoverName = VLC->generaltexth->names[map->objects[no]->ID];
  1149. }
  1150. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  1151. /*********give starting hero****************************************/
  1152. for(int i=0;i<PLAYER_LIMIT;i++)
  1153. {
  1154. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==RoE))
  1155. {
  1156. int3 hpos = map->players[i].posOfMainTown;
  1157. hpos.x+=1;// hpos.y+=1;
  1158. int j;
  1159. for(j=0; j<scenarioOps->playerInfos.size(); j++)
  1160. if(scenarioOps->playerInfos[j].color == i)
  1161. break;
  1162. if(j == scenarioOps->playerInfos.size())
  1163. continue;
  1164. int h=pickHero(i);
  1165. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(34,h,hpos,i));
  1166. nnn->id = map->objects.size();
  1167. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  1168. for(int o=0;o<map->towns.size();o++) //find main town
  1169. {
  1170. if(map->towns[o]->pos == hpos)
  1171. {
  1172. map->towns[o]->visitingHero = nnn;
  1173. nnn->visitedTown = map->towns[o];
  1174. nnn->inTownGarrison = false;
  1175. break;
  1176. }
  1177. }
  1178. nnn->initHero();
  1179. map->heroes.push_back(nnn);
  1180. map->objects.push_back(nnn);
  1181. map->addBlockVisTiles(nnn);
  1182. }
  1183. }
  1184. /*********creating players entries in gs****************************************/
  1185. for (int i=0; i<scenarioOps->playerInfos.size();i++)
  1186. {
  1187. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  1188. ins.second.color=ins.first;
  1189. ins.second.serial=i;
  1190. players.insert(ins);
  1191. }
  1192. /******************RESOURCES****************************************************/
  1193. //TODO: computer player should receive other amount of resource than computer (depending on difficulty)
  1194. std::vector<int> startres;
  1195. std::ifstream tis("config/startres.txt");
  1196. int k;
  1197. for (int j=0;j<scenarioOps->difficulty;j++)
  1198. {
  1199. tis >> k;
  1200. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1201. tis>>k;
  1202. }
  1203. tis >> k;
  1204. for (int i=0;i<RESOURCE_QUANTITY;i++)
  1205. {
  1206. tis >> k;
  1207. startres.push_back(k);
  1208. }
  1209. tis.close();
  1210. tis.clear();
  1211. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1212. {
  1213. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1214. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1215. (*i).second.resources[x] = startres[x];
  1216. }
  1217. tis.open("config/resources.txt");
  1218. tis >> k;
  1219. int pom;
  1220. for(int i=0;i<k;i++)
  1221. {
  1222. tis >> pom;
  1223. resVals.push_back(pom);
  1224. }
  1225. /*************************HEROES************************************************/
  1226. std::set<int> hids;
  1227. for(int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1228. if(map->allowedHeroes[i])
  1229. hids.insert(i);
  1230. for (int i=0; i<map->heroes.size();i++) //heroes instances initialization
  1231. {
  1232. if (map->heroes[i]->getOwner()<0)
  1233. {
  1234. tlog2 << "Warning - hero with uninitialized owner!\n";
  1235. continue;
  1236. }
  1237. CGHeroInstance * vhi = (map->heroes[i]);
  1238. vhi->initHero();
  1239. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1240. hids.erase(vhi->subID);
  1241. }
  1242. for(int i=0; i<map->predefinedHeroes.size(); i++)
  1243. {
  1244. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1245. continue;
  1246. map->predefinedHeroes[i]->initHero();
  1247. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1248. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1249. hids.erase(map->predefinedHeroes[i]->subID);
  1250. }
  1251. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go into the pool
  1252. {
  1253. CGHeroInstance * vhi = new CGHeroInstance();
  1254. vhi->initHero(hid);
  1255. hpool.heroesPool[hid] = vhi;
  1256. hpool.pavailable[hid] = 0xff;
  1257. }
  1258. for(int i=0; i<map->disposedHeroes.size(); i++)
  1259. {
  1260. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1261. }
  1262. /*************************FOG**OF**WAR******************************************/
  1263. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1264. {
  1265. k->second.fogOfWarMap.resize(map->width);
  1266. for(int g=0; g<map->width; ++g)
  1267. k->second.fogOfWarMap[g].resize(map->height);
  1268. for(int g=-0; g<map->width; ++g)
  1269. for(int h=0; h<map->height; ++h)
  1270. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1271. for(int g=0; g<map->width; ++g)
  1272. for(int h=0; h<map->height; ++h)
  1273. for(int v=0; v<map->twoLevel+1; ++v)
  1274. k->second.fogOfWarMap[g][h][v] = 0;
  1275. for(int xd=0; xd<map->width; ++xd) //revealing part of map around heroes
  1276. {
  1277. for(int yd=0; yd<map->height; ++yd)
  1278. {
  1279. for(int ch=0; ch<k->second.heroes.size(); ++ch)
  1280. {
  1281. int deltaX = (k->second.heroes[ch]->getPosition(false).x-xd)*(k->second.heroes[ch]->getPosition(false).x-xd);
  1282. int deltaY = (k->second.heroes[ch]->getPosition(false).y-yd)*(k->second.heroes[ch]->getPosition(false).y-yd);
  1283. if(deltaX+deltaY<k->second.heroes[ch]->getSightDistance()*k->second.heroes[ch]->getSightDistance())
  1284. k->second.fogOfWarMap[xd][yd][k->second.heroes[ch]->getPosition(false).z] = 1;
  1285. }
  1286. }
  1287. }
  1288. //starting bonus
  1289. if(si->playerInfos[k->second.serial].bonus==brandom)
  1290. si->playerInfos[k->second.serial].bonus = ran()%3;
  1291. switch(si->playerInfos[k->second.serial].bonus)
  1292. {
  1293. case bgold:
  1294. k->second.resources[6] += 500 + (ran()%6)*100;
  1295. break;
  1296. case bresource:
  1297. {
  1298. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1299. if(res == 127)
  1300. {
  1301. k->second.resources[0] += 5 + ran()%6;
  1302. k->second.resources[2] += 5 + ran()%6;
  1303. }
  1304. else
  1305. {
  1306. k->second.resources[res] += 3 + ran()%4;
  1307. }
  1308. break;
  1309. }
  1310. case bartifact:
  1311. {
  1312. if(!k->second.heroes.size())
  1313. {
  1314. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1315. break;
  1316. }
  1317. CArtifact *toGive;
  1318. do
  1319. {
  1320. toGive = VLC->arth->treasures[ran() % VLC->arth->treasures.size()];
  1321. } while (!map->allowedArtifact[toGive->id]);
  1322. CGHeroInstance *hero = k->second.heroes[0];
  1323. std::vector<ui16>::iterator slot = vstd::findFirstNot(hero->artifWorn,toGive->possibleSlots);
  1324. if(slot!=toGive->possibleSlots.end())
  1325. hero->artifWorn[*slot] = toGive->id;
  1326. else
  1327. hero->artifacts.push_back(toGive->id);
  1328. }
  1329. }
  1330. }
  1331. /****************************TOWNS************************************************/
  1332. for (int i=0;i<map->towns.size();i++)
  1333. {
  1334. CGTownInstance * vti =(map->towns[i]);
  1335. if(!vti->town)
  1336. vti->town = &VLC->townh->towns[vti->subID];
  1337. if (vti->name.length()==0) // if town hasn't name we draw it
  1338. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1339. //init buildings
  1340. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1341. {
  1342. vti->builtBuildings.erase(-50);
  1343. vti->builtBuildings.insert(10);
  1344. vti->builtBuildings.insert(5);
  1345. vti->builtBuildings.insert(30);
  1346. if(ran()%2)
  1347. vti->builtBuildings.insert(31);
  1348. }
  1349. //init spells
  1350. vti->spells.resize(SPELL_LEVELS);
  1351. CSpell *s;
  1352. for(int z=0; z<vti->obligatorySpells.size();z++)
  1353. {
  1354. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1355. vti->spells[s->level-1].push_back(s->id);
  1356. vti->possibleSpells -= s->id;
  1357. }
  1358. while(vti->possibleSpells.size())
  1359. {
  1360. ui32 total=0, sel=-1;
  1361. for(int ps=0;ps<vti->possibleSpells.size();ps++)
  1362. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1363. int r = (total)? ran()%total : -1;
  1364. for(int ps=0; ps<vti->possibleSpells.size();ps++)
  1365. {
  1366. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1367. if(r<0)
  1368. {
  1369. sel = ps;
  1370. break;
  1371. }
  1372. }
  1373. if(sel<0)
  1374. sel=0;
  1375. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1376. vti->spells[s->level-1].push_back(s->id);
  1377. vti->possibleSpells -= s->id;
  1378. }
  1379. //init garrisons
  1380. for (std::map<si32,std::pair<ui32,si32> >::iterator j=vti->army.slots.begin(); j!=vti->army.slots.end();j++)
  1381. {
  1382. if(j->second.first > 196 && j->second.first < 211)
  1383. {
  1384. if(j->second.first%2)
  1385. j->second.first = vti->town->basicCreatures[ (j->second.first-197) / 2 ];
  1386. else
  1387. j->second.first = vti->town->upgradedCreatures[ (j->second.first-197) / 2 ];
  1388. }
  1389. }
  1390. players[vti->getOwner()].towns.push_back(vti);
  1391. }
  1392. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1393. {
  1394. if(k->first==-1 || k->first==255)
  1395. continue;
  1396. for(int xd=0; xd<map->width; ++xd) //revealing part of map around towns
  1397. {
  1398. for(int yd=0; yd<map->height; ++yd)
  1399. {
  1400. for(int ch=0; ch<k->second.towns.size(); ++ch)
  1401. {
  1402. int deltaX = (k->second.towns[ch]->pos.x-xd)*(k->second.towns[ch]->pos.x-xd);
  1403. int deltaY = (k->second.towns[ch]->pos.y-yd)*(k->second.towns[ch]->pos.y-yd);
  1404. if(deltaX+deltaY<k->second.towns[ch]->getSightDistance()*k->second.towns[ch]->getSightDistance())
  1405. k->second.fogOfWarMap[xd][yd][k->second.towns[ch]->pos.z] = 1;
  1406. }
  1407. }
  1408. }
  1409. //init visiting and garrisoned heroes
  1410. for(int l=0; l<k->second.heroes.size();l++)
  1411. {
  1412. for(int m=0; m<k->second.towns.size();m++)
  1413. {
  1414. int3 vistile = k->second.towns[m]->pos; vistile.x--; //tile next to the entrance
  1415. if(vistile == k->second.heroes[l]->pos || k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1416. {
  1417. k->second.towns[m]->visitingHero = k->second.heroes[l];
  1418. k->second.heroes[l]->visitedTown = k->second.towns[m];
  1419. k->second.heroes[l]->inTownGarrison = false;
  1420. if(k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1421. k->second.heroes[l]->pos.x -= 1;
  1422. break;
  1423. }
  1424. }
  1425. }
  1426. }
  1427. for(int i=0; i<map->defy.size(); i++)
  1428. {
  1429. map->defy[i]->serial = i;
  1430. }
  1431. for(int i=0; i<map->objects.size(); i++)
  1432. map->objects[i]->initObj();
  1433. }
  1434. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1435. {
  1436. return true;
  1437. }
  1438. int CGameState::battleGetStack(int pos)
  1439. {
  1440. if(!curB)
  1441. return -1;
  1442. for(int g=0; g<curB->stacks.size(); ++g)
  1443. {
  1444. if((curB->stacks[g]->position == pos
  1445. || (curB->stacks[g]->creature->isDoubleWide()
  1446. &&( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos)
  1447. || (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos) )
  1448. ))
  1449. && curB->stacks[g]->alive()
  1450. )
  1451. return curB->stacks[g]->ID;
  1452. }
  1453. return -1;
  1454. }
  1455. UpgradeInfo CGameState::getUpgradeInfo(CArmedInstance *obj, int stackPos)
  1456. {
  1457. UpgradeInfo ret;
  1458. CCreature *base = &VLC->creh->creatures[obj->army.slots[stackPos].first];
  1459. if((obj->ID == 98) || ((obj->ID == 34) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
  1460. {
  1461. CGTownInstance * t;
  1462. if(obj->ID == 98)
  1463. t = static_cast<CGTownInstance *>(const_cast<CArmedInstance *>(obj));
  1464. else
  1465. t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
  1466. for(std::set<si32>::iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++)
  1467. {
  1468. if( (*i) >= 37 && (*i) < 44 ) //upgraded creature dwelling
  1469. {
  1470. int nid = t->town->upgradedCreatures[(*i)-37]; //upgrade offered by that building
  1471. if(base->upgrades.find(nid) != base->upgrades.end()) //possible upgrade
  1472. {
  1473. ret.newID.push_back(nid);
  1474. ret.cost.push_back(std::set<std::pair<int,int> >());
  1475. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1476. {
  1477. int dif = VLC->creh->creatures[nid].cost[j] - base->cost[j];
  1478. if(dif)
  1479. ret.cost[ret.cost.size()-1].insert(std::make_pair(j,dif));
  1480. }
  1481. }
  1482. }
  1483. }//end for
  1484. }
  1485. //TODO: check if hero ability makes some upgrades possible
  1486. if(ret.newID.size())
  1487. ret.oldID = base->idNumber;
  1488. return ret;
  1489. }
  1490. float CGameState::getMarketEfficiency( int player, int mode/*=0*/ )
  1491. {
  1492. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1493. if(mode) return -1; //todo - support other modes
  1494. int mcount = 0;
  1495. for(int i=0;i<players[player].towns.size();i++)
  1496. if(vstd::contains(players[player].towns[i]->builtBuildings,14))
  1497. mcount++;
  1498. float ret = std::min(((float)mcount+1.0f)/20.0f,0.5f);
  1499. return ret;
  1500. }
  1501. std::set<int3> CGameState::tilesToReveal(int3 pos, int radious, int player) const
  1502. {
  1503. std::set<int3> ret;
  1504. int xbeg = pos.x - radious - 2;
  1505. if(xbeg < 0)
  1506. xbeg = 0;
  1507. int xend = pos.x + radious + 2;
  1508. if(xend >= map->width)
  1509. xend = map->width;
  1510. int ybeg = pos.y - radious - 2;
  1511. if(ybeg < 0)
  1512. ybeg = 0;
  1513. int yend = pos.y + radious + 2;
  1514. if(yend >= map->height)
  1515. yend = map->height;
  1516. for(int xd=xbeg; xd<xend; ++xd) //revealing part of map around heroes
  1517. {
  1518. for(int yd=ybeg; yd<yend; ++yd)
  1519. {
  1520. int deltaX = (pos.x-xd)*(pos.x-xd);
  1521. int deltaY = (pos.y-yd)*(pos.y-yd);
  1522. if(deltaX+deltaY<radious*radious)
  1523. {
  1524. if(player<0 || players.find(player)->second.fogOfWarMap[xd][yd][pos.z]==0)
  1525. {
  1526. ret.insert(int3(xd,yd,pos.z));
  1527. }
  1528. }
  1529. }
  1530. }
  1531. return ret;
  1532. }
  1533. void CGameState::loadTownDInfos()
  1534. {
  1535. for(int i=0;i<F_NUMBER;i++)
  1536. {
  1537. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1538. forts[i] = VLC->dobjinfo->castles[i];
  1539. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1540. }
  1541. }
  1542. void CGameState::setObjProperty( SetObjectProperty * p )
  1543. {
  1544. CGObjectInstance *obj = map->objects[p->id];
  1545. switch(p->what)
  1546. {
  1547. case 1:
  1548. obj->tempOwner = p->val;
  1549. break;
  1550. case 2:
  1551. obj->blockVisit = p->val;
  1552. break;
  1553. case 3:
  1554. static_cast<CArmedInstance*>(obj)->army.slots[0].second = p->val;
  1555. break;
  1556. case 4:
  1557. static_cast<CGVisitableOPH*>(obj)->visitors.insert(p->val);
  1558. break;
  1559. case 5:
  1560. static_cast<CGVisitableOPW*>(obj)->visited = p->val;
  1561. break;
  1562. }
  1563. }
  1564. int BattleInfo::calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting)
  1565. {
  1566. int attackerAttackBonus = attacker->creature->attack + (attackerHero ? attackerHero->getPrimSkillLevel(0) : 0);
  1567. if(attacker->getEffect(56)) //frenzy for attacker
  1568. {
  1569. attackerAttackBonus += (VLC->spellh->spells[attacker->getEffect(56)->id].powers[attacker->getEffect(56)->level]/100.0) *(attacker->creature->defence + (attackerHero ? attackerHero->getPrimSkillLevel(1) : 0));
  1570. }
  1571. int defenderDefenseBonus = defender->creature->defence + (defendingHero ? defendingHero->getPrimSkillLevel(1) : 0);
  1572. if(defender->getEffect(56)) //frenzy for defender
  1573. {
  1574. defenderDefenseBonus = 0;
  1575. }
  1576. int attackDefenseBonus = attackerAttackBonus - defenderDefenseBonus;
  1577. if(defender->getEffect(48)) //defender's prayer handling
  1578. {
  1579. attackDefenseBonus -= VLC->spellh->spells[defender->getEffect(48)->id].powers[defender->getEffect(48)->level];
  1580. }
  1581. if(attacker->getEffect(48)) //attacker's prayer handling
  1582. {
  1583. attackDefenseBonus += VLC->spellh->spells[attacker->getEffect(48)->id].powers[attacker->getEffect(48)->level];
  1584. }
  1585. if(defender->getEffect(46)) //stone skin handling
  1586. {
  1587. attackDefenseBonus -= VLC->spellh->spells[defender->getEffect(46)->id].powers[defender->getEffect(46)->level];
  1588. }
  1589. if(attacker->getEffect(45)) //weakness handling
  1590. {
  1591. attackDefenseBonus -= VLC->spellh->spells[attacker->getEffect(45)->id].powers[attacker->getEffect(45)->level];
  1592. }
  1593. if(!shooting && attacker->getEffect(43)) //bloodlust handling
  1594. {
  1595. attackDefenseBonus += VLC->spellh->spells[attacker->getEffect(43)->id].powers[attacker->getEffect(43)->level];
  1596. }
  1597. int damageBase = 0;
  1598. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  1599. {
  1600. damageBase = attacker->creature->damageMin;
  1601. damageBase -= VLC->spellh->spells[attacker->getEffect(42)->id].powers[attacker->getEffect(42)->level];
  1602. }
  1603. else if(attacker->getEffect(41)) //bless handling
  1604. {
  1605. damageBase = attacker->creature->damageMax;
  1606. damageBase += VLC->spellh->spells[attacker->getEffect(41)->id].powers[attacker->getEffect(41)->level];
  1607. }
  1608. else if(attacker->creature->damageMax == attacker->creature->damageMin) //constant damage
  1609. {
  1610. damageBase = attacker->creature->damageMin;
  1611. }
  1612. else
  1613. {
  1614. damageBase = rand()%(attacker->creature->damageMax - attacker->creature->damageMin) + attacker->creature->damageMin + 1;
  1615. }
  1616. float dmgBonusMultiplier = 1.0f;
  1617. if(attackDefenseBonus < 0) //decreasing dmg
  1618. {
  1619. if(0.02f * (-attackDefenseBonus) > 0.3f)
  1620. {
  1621. dmgBonusMultiplier += -0.3f;
  1622. }
  1623. else
  1624. {
  1625. dmgBonusMultiplier += 0.02f * attackDefenseBonus;
  1626. }
  1627. }
  1628. else //increasing dmg
  1629. {
  1630. if(0.05f * attackDefenseBonus > 4.0f)
  1631. {
  1632. dmgBonusMultiplier += 4.0f;
  1633. }
  1634. else
  1635. {
  1636. dmgBonusMultiplier += 0.05f * attackDefenseBonus;
  1637. }
  1638. }
  1639. //handling secondary abilities
  1640. if(attackerHero)
  1641. {
  1642. if(shooting)
  1643. {
  1644. switch(attackerHero->getSecSkillLevel(1)) //archery
  1645. {
  1646. case 1: //basic
  1647. dmgBonusMultiplier *= 1.1f;
  1648. break;
  1649. case 2: //advanced
  1650. dmgBonusMultiplier *= 1.25f;
  1651. break;
  1652. case 3: //expert
  1653. dmgBonusMultiplier *= 1.5f;
  1654. break;
  1655. }
  1656. }
  1657. else
  1658. {
  1659. switch(attackerHero->getSecSkillLevel(22)) //offence
  1660. {
  1661. case 1: //basic
  1662. dmgBonusMultiplier *= 1.1f;
  1663. break;
  1664. case 2: //advanced
  1665. dmgBonusMultiplier *= 1.2f;
  1666. break;
  1667. case 3: //expert
  1668. dmgBonusMultiplier *= 1.3f;
  1669. break;
  1670. }
  1671. }
  1672. }
  1673. if(defendingHero)
  1674. {
  1675. switch(defendingHero->getSecSkillLevel(23)) //armourer
  1676. {
  1677. case 1: //basic
  1678. dmgBonusMultiplier *= 0.95f;
  1679. break;
  1680. case 2: //advanced
  1681. dmgBonusMultiplier *= 0.9f;
  1682. break;
  1683. case 3: //expert
  1684. dmgBonusMultiplier *= 0.85f;
  1685. break;
  1686. }
  1687. }
  1688. //handling spell effects
  1689. if(!shooting && defender->getEffect(27)) //shield
  1690. {
  1691. if(defender->getEffect(27)->level<=1) //none or basic
  1692. dmgBonusMultiplier *= 0.85f;
  1693. else //adv or expert
  1694. dmgBonusMultiplier *= 0.7f;
  1695. }
  1696. if(shooting && defender->getEffect(28)) //air shield
  1697. {
  1698. if(defender->getEffect(28)->level<=1) //none or basic
  1699. dmgBonusMultiplier *= 0.75f;
  1700. else //adv or expert
  1701. dmgBonusMultiplier *= 0.5f;
  1702. }
  1703. if(attacker->getEffect(42)) //curse, second part of handling
  1704. {
  1705. if(attacker->getEffect(42)->level>=2) //adv or expert
  1706. dmgBonusMultiplier *= 0.8f;
  1707. }
  1708. return (float)damageBase * (float)attacker->amount * dmgBonusMultiplier;
  1709. }
  1710. void BattleInfo::calculateCasualties( std::set<std::pair<ui32,si32> > *casualties )
  1711. {
  1712. for(int i=0; i<stacks.size();i++)//setting casualties
  1713. {
  1714. if(!stacks[i]->alive())
  1715. {
  1716. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount));
  1717. }
  1718. else if(stacks[i]->amount != stacks[i]->baseAmount)
  1719. {
  1720. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount - stacks[i]->amount));
  1721. }
  1722. }
  1723. }
  1724. CStack * BattleInfo::getNextStack()
  1725. {
  1726. CStack *current = getStack(activeStack);
  1727. for (int i = 0; i < stacks.size(); i++) //find fastest not moved/waited stack (stacks vector is sorted by speed)
  1728. {
  1729. if(vstd::contains(stacks[i]->state,DEFENDING)
  1730. ||vstd::contains(stacks[i]->state,WAITING)
  1731. ||vstd::contains(stacks[i]->state,MOVED)
  1732. ||!stacks[i]->alive()
  1733. )
  1734. continue;
  1735. return stacks[i];
  1736. }
  1737. for (int i = stacks.size() - 1; i >= 0 ; i--) //find slowest waiting stack
  1738. {
  1739. if(vstd::contains(stacks[i]->state,DEFENDING)
  1740. ||vstd::contains(stacks[i]->state,MOVED)
  1741. ||!stacks[i]->alive()
  1742. )
  1743. continue;
  1744. return stacks[i];
  1745. }
  1746. return NULL; //all stacks moved or defending!
  1747. }
  1748. std::vector<CStack> BattleInfo::getStackQueue()
  1749. {
  1750. std::vector<CStack> ret;
  1751. std::vector<int> taken; //if non-zero value, corresponding stack has been placed in ret
  1752. taken.resize(stacks.size());
  1753. for(int g=0; g<taken.size(); ++g)
  1754. {
  1755. taken[g] = 0;
  1756. }
  1757. 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
  1758. {
  1759. for(int gc=0; gc<stacks.size(); ++gc)
  1760. {
  1761. int id = -1, speed = -1;
  1762. for(int i=0; i<stacks.size(); ++i) //find not waited stacks only
  1763. {
  1764. if((moved == 1 ||!vstd::contains(stacks[i]->state,DEFENDING))
  1765. && stacks[i]->alive()
  1766. && (moved == 1 || !vstd::contains(stacks[i]->state,MOVED))
  1767. && !vstd::contains(stacks[i]->state,WAITING)
  1768. && taken[i]==0)
  1769. {
  1770. if(speed == -1 || stacks[i]->speed() > speed)
  1771. {
  1772. id = i;
  1773. speed = stacks[i]->speed();
  1774. }
  1775. }
  1776. }
  1777. if(id != -1)
  1778. {
  1779. ret.push_back(*stacks[id]);
  1780. taken[id] = 1;
  1781. }
  1782. else //choose something from not moved stacks
  1783. {
  1784. int id = -1, speed = 10000; //infinite speed
  1785. for(int i=0; i<stacks.size(); ++i) //find waited stacks only
  1786. {
  1787. if((moved == 1 ||!vstd::contains(stacks[i]->state,DEFENDING))
  1788. && stacks[i]->alive()
  1789. && (moved == 1 || !vstd::contains(stacks[i]->state,MOVED))
  1790. && vstd::contains(stacks[i]->state,WAITING)
  1791. && taken[i]==0)
  1792. {
  1793. if(stacks[i]->speed() < speed) //slowest one
  1794. {
  1795. id = i;
  1796. speed = stacks[i]->speed();
  1797. }
  1798. }
  1799. }
  1800. if(id != -1)
  1801. {
  1802. ret.push_back(*stacks[id]);
  1803. taken[id] = 1;
  1804. }
  1805. else
  1806. {
  1807. break; //no stacks have been found, so none of them will be found in next iterations
  1808. }
  1809. }
  1810. }
  1811. }
  1812. return ret;
  1813. }