CGameState.cpp 46 KB

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