CGameState.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584
  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)
  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. curB->stacks[i]->counterAttacks = 1;
  665. break;
  666. }
  667. case 3002:
  668. {
  669. BattleSetActiveStack *ns = static_cast<BattleSetActiveStack*>(pack);
  670. curB->activeStack = ns->stack;
  671. break;
  672. }
  673. case 3003:
  674. {
  675. BattleResult *br = static_cast<BattleResult*>(pack);
  676. //TODO: give exp, artifacts to winner, decrease armies (casualties)
  677. for(unsigned i=0;i<curB->stacks.size();i++)
  678. delete curB->stacks[i];
  679. delete curB;
  680. curB = NULL;
  681. break;
  682. }
  683. case 3004:
  684. {
  685. BattleStackMoved *br = static_cast<BattleStackMoved*>(pack);
  686. curB->getStack(br->stack)->position = br->tile;
  687. break;
  688. }
  689. case 3005:
  690. {
  691. BattleStackAttacked *br = static_cast<BattleStackAttacked*>(pack);
  692. CStack * at = curB->getStack(br->stackAttacked);
  693. at->amount = br->newAmount;
  694. at->firstHPleft = br->newHP;
  695. if(br->killed())
  696. at->state -= ALIVE;
  697. break;
  698. }
  699. case 3006:
  700. {
  701. BattleAttack *br = static_cast<BattleAttack*>(pack);
  702. CStack *attacker = curB->getStack(br->stackAttacking);
  703. if(br->counter())
  704. attacker->counterAttacks--;
  705. if(br->shot())
  706. attacker->shots--;
  707. applyNL(&br->bsa);
  708. break;
  709. }
  710. case 3009:
  711. {
  712. SpellCasted *sc = static_cast<SpellCasted*>(pack);
  713. CGHeroInstance *h = (sc->side) ? getHero(curB->hero2) : getHero(curB->hero1);
  714. if(h)
  715. h->mana -= VLC->spellh->spells[sc->id].costs[sc->skill];
  716. //TODO: counter
  717. break;
  718. }
  719. case 3010:
  720. {
  721. SetStackEffect *sc = static_cast<SetStackEffect*>(pack);
  722. CStack *stack = curB->getStack(sc->stack);
  723. stack->effects.push_back(sc->effect);
  724. break;
  725. }
  726. }
  727. }
  728. void CGameState::apply(IPack * pack)
  729. {
  730. while(!mx->try_lock())
  731. boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  732. applyNL(pack);
  733. mx->unlock();
  734. }
  735. int CGameState::pickHero(int owner)
  736. {
  737. int h=-1;
  738. if(!map->getHero(h = scenarioOps->getIthPlayersSettings(owner).hero,0) && h>=0) //we haven't used selected hero
  739. return h;
  740. int f = scenarioOps->getIthPlayersSettings(owner).castle;
  741. int i=0;
  742. do //try to find free hero of our faction
  743. {
  744. i++;
  745. h = scenarioOps->getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  746. } while( map->getHero(h) && i<175);
  747. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  748. {
  749. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  750. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  751. if(!map->getHero(j))
  752. h=j;
  753. }
  754. return h;
  755. }
  756. CGHeroInstance *CGameState::getHero(int objid)
  757. {
  758. if(objid<0 || objid>=map->objects.size())
  759. return NULL;
  760. return static_cast<CGHeroInstance *>(map->objects[objid]);
  761. }
  762. CGTownInstance *CGameState::getTown(int objid)
  763. {
  764. if(objid<0 || objid>=map->objects.size())
  765. return NULL;
  766. return static_cast<CGTownInstance *>(map->objects[objid]);
  767. }
  768. std::pair<int,int> CGameState::pickObject(CGObjectInstance *obj)
  769. {
  770. switch(obj->ID)
  771. {
  772. case 65: //random artifact
  773. return std::pair<int,int>(5,(ran()%136)+7); //tylko sensowny zakres - na poczatku sa katapulty itp, na koncu specjalne i blanki
  774. case 66: //random treasure artifact
  775. return std::pair<int,int>(5,VLC->arth->treasures[ran()%VLC->arth->treasures.size()]->id);
  776. case 67: //random minor artifact
  777. return std::pair<int,int>(5,VLC->arth->minors[ran()%VLC->arth->minors.size()]->id);
  778. case 68: //random major artifact
  779. return std::pair<int,int>(5,VLC->arth->majors[ran()%VLC->arth->majors.size()]->id);
  780. case 69: //random relic artifact
  781. return std::pair<int,int>(5,VLC->arth->relics[ran()%VLC->arth->relics.size()]->id);
  782. case 70: //random hero
  783. {
  784. return std::pair<int,int>(34,pickHero(obj->tempOwner));
  785. }
  786. case 71: //random monster
  787. {
  788. int r;
  789. do
  790. {
  791. r = ran()%197;
  792. } while (vstd::contains(VLC->creh->notUsedMonsters,r));
  793. return std::pair<int,int>(54,r);
  794. }
  795. case 72: //random monster lvl1
  796. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  797. case 73: //random monster lvl2
  798. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  799. case 74: //random monster lvl3
  800. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  801. case 75: //random monster lvl4
  802. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  803. case 76: //random resource
  804. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  805. case 77: //random town
  806. {
  807. int align = ((CGTownInstance*)obj)->alignment,
  808. f;
  809. if(align>PLAYER_LIMIT-1)//same as owner / random
  810. {
  811. if(obj->tempOwner > PLAYER_LIMIT-1)
  812. f = -1; //random
  813. else
  814. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  815. }
  816. else
  817. {
  818. f = scenarioOps->getIthPlayersSettings(align).castle;
  819. }
  820. if(f<0) f = ran()%VLC->townh->towns.size();
  821. return std::pair<int,int>(98,f);
  822. }
  823. case 162: //random monster lvl5
  824. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  825. case 163: //random monster lvl6
  826. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  827. case 164: //random monster lvl7
  828. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  829. case 216: //random dwelling
  830. {
  831. int faction = ran()%F_NUMBER;
  832. CCreGen2ObjInfo* info =(CCreGen2ObjInfo*)obj->info;
  833. if (info->asCastle)
  834. {
  835. for(int i=0;i<map->objects.size();i++)
  836. {
  837. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  838. {
  839. randomizeObject(map->objects[i]); //we have to randomize the castle first
  840. faction = map->objects[i]->subID;
  841. break;
  842. }
  843. else if(map->objects[i]->ID==98 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  844. {
  845. faction = map->objects[i]->subID;
  846. break;
  847. }
  848. }
  849. }
  850. else
  851. {
  852. while((!(info->castles[0]&(1<<faction))))
  853. {
  854. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  855. break;
  856. faction = ran()%F_NUMBER;
  857. }
  858. }
  859. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  860. int cid = VLC->townh->towns[faction].basicCreatures[level];
  861. for(int i=0;i<VLC->objh->cregens.size();i++)
  862. if(VLC->objh->cregens[i]==cid)
  863. return std::pair<int,int>(17,i);
  864. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  865. return std::pair<int,int>(17,0);
  866. }
  867. case 217:
  868. {
  869. int faction = ran()%F_NUMBER;
  870. CCreGenObjInfo* info =(CCreGenObjInfo*)obj->info;
  871. if (info->asCastle)
  872. {
  873. for(int i=0;i<map->objects.size();i++)
  874. {
  875. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  876. {
  877. randomizeObject(map->objects[i]); //we have to randomize the castle first
  878. faction = map->objects[i]->subID;
  879. break;
  880. }
  881. else if(map->objects[i]->ID==98 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  882. {
  883. faction = map->objects[i]->subID;
  884. break;
  885. }
  886. }
  887. }
  888. else
  889. {
  890. while((!(info->castles[0]&(1<<faction))))
  891. {
  892. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  893. break;
  894. faction = ran()%F_NUMBER;
  895. }
  896. }
  897. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  898. for(int i=0;i<VLC->objh->cregens.size();i++)
  899. if(VLC->objh->cregens[i]==cid)
  900. return std::pair<int,int>(17,i);
  901. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  902. return std::pair<int,int>(17,0);
  903. }
  904. case 218:
  905. {
  906. CCreGen3ObjInfo* info =(CCreGen3ObjInfo*)obj->info;
  907. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  908. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  909. for(int i=0;i<VLC->objh->cregens.size();i++)
  910. if(VLC->objh->cregens[i]==cid)
  911. return std::pair<int,int>(17,i);
  912. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  913. return std::pair<int,int>(17,0);
  914. }
  915. }
  916. return std::pair<int,int>(-1,-1);
  917. }
  918. void CGameState::randomizeObject(CGObjectInstance *cur)
  919. {
  920. std::pair<int,int> ran = pickObject(cur);
  921. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  922. {
  923. if(cur->ID==98) //town - set def
  924. {
  925. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  926. if(t->hasCapitol())
  927. t->defInfo = capitols[t->subID];
  928. else if(t->hasFort())
  929. t->defInfo = forts[t->subID];
  930. else
  931. t->defInfo = villages[t->subID];
  932. }
  933. return;
  934. }
  935. else if(ran.first==34)//special code for hero
  936. {
  937. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  938. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  939. cur->ID = ran.first;
  940. h->portrait = cur->subID = ran.second;
  941. h->type = VLC->heroh->heroes[ran.second];
  942. map->heroes.push_back(h);
  943. return; //TODO: maybe we should do something with definfo?
  944. }
  945. else if(ran.first==98)//special code for town
  946. {
  947. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  948. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  949. cur->ID = ran.first;
  950. cur->subID = ran.second;
  951. t->town = &VLC->townh->towns[ran.second];
  952. if(t->hasCapitol())
  953. t->defInfo = capitols[t->subID];
  954. else if(t->hasFort())
  955. t->defInfo = forts[t->subID];
  956. else
  957. t->defInfo = villages[t->subID];
  958. map->towns.push_back(t);
  959. return;
  960. }
  961. //we have to replace normal random object
  962. cur->ID = ran.first;
  963. cur->subID = ran.second;
  964. map->defs.insert(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  965. if(!cur->defInfo)
  966. {
  967. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  968. return;
  969. }
  970. }
  971. int CGameState::getDate(int mode) const
  972. {
  973. int temp;
  974. switch (mode)
  975. {
  976. case 0:
  977. return day;
  978. break;
  979. case 1:
  980. temp = (day)%7;
  981. if (temp)
  982. return temp;
  983. else return 7;
  984. break;
  985. case 2:
  986. temp = ((day-1)/7)+1;
  987. if (!(temp%4))
  988. return 4;
  989. else
  990. return (temp%4);
  991. break;
  992. case 3:
  993. return ((day-1)/28)+1;
  994. break;
  995. }
  996. return 0;
  997. }
  998. CGameState::CGameState()
  999. {
  1000. mx = new boost::shared_mutex();
  1001. }
  1002. CGameState::~CGameState()
  1003. {
  1004. delete mx;
  1005. }
  1006. void CGameState::init(StartInfo * si, Mapa * map, int Seed)
  1007. {
  1008. day = 0;
  1009. seed = Seed;
  1010. ran.seed((boost::int32_t)seed);
  1011. scenarioOps = si;
  1012. this->map = map;
  1013. for(int i=0;i<F_NUMBER;i++)
  1014. {
  1015. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1016. forts[i] = VLC->dobjinfo->castles[i];
  1017. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1018. }
  1019. //picking random factions for players
  1020. for(int i=0;i<scenarioOps->playerInfos.size();i++)
  1021. {
  1022. if(scenarioOps->playerInfos[i].castle==-1)
  1023. {
  1024. int f;
  1025. do
  1026. {
  1027. f = ran()%F_NUMBER;
  1028. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  1029. scenarioOps->playerInfos[i].castle = f;
  1030. }
  1031. }
  1032. //randomizing objects
  1033. for(int no=0; no<map->objects.size(); ++no)
  1034. {
  1035. randomizeObject(map->objects[no]);
  1036. if(map->objects[no]->ID==26)
  1037. {
  1038. map->objects[no]->defInfo->handler=NULL;
  1039. map->removeBlockVisTiles(map->objects[no]);
  1040. map->objects[no]->defInfo->blockMap[5] = 255;
  1041. map->addBlockVisTiles(map->objects[no]);
  1042. }
  1043. map->objects[no]->hoverName = VLC->objh->names[map->objects[no]->ID];
  1044. }
  1045. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  1046. /*********give starting hero****************************************/
  1047. for(int i=0;i<PLAYER_LIMIT;i++)
  1048. {
  1049. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==RoE))
  1050. {
  1051. int3 hpos = map->players[i].posOfMainTown;
  1052. hpos.x+=1;// hpos.y+=1;
  1053. int j;
  1054. for(j=0; j<scenarioOps->playerInfos.size(); j++)
  1055. if(scenarioOps->playerInfos[j].color == i)
  1056. break;
  1057. if(j == scenarioOps->playerInfos.size())
  1058. continue;
  1059. int h=pickHero(i);
  1060. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(34,h,hpos,i));
  1061. nnn->id = map->objects.size();
  1062. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  1063. for(int o=0;o<map->towns.size();o++) //find main town
  1064. {
  1065. if(map->towns[o]->pos == hpos)
  1066. {
  1067. map->towns[o]->visitingHero = nnn;
  1068. nnn->visitedTown = map->towns[o];
  1069. nnn->inTownGarrison = false;
  1070. break;
  1071. }
  1072. }
  1073. nnn->initHero();
  1074. map->heroes.push_back(nnn);
  1075. map->objects.push_back(nnn);
  1076. map->addBlockVisTiles(nnn);
  1077. }
  1078. }
  1079. /*********creating players entries in gs****************************************/
  1080. for (int i=0; i<scenarioOps->playerInfos.size();i++)
  1081. {
  1082. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  1083. ins.second.color=ins.first;
  1084. ins.second.serial=i;
  1085. players.insert(ins);
  1086. }
  1087. /******************RESOURCES****************************************************/
  1088. //TODO: computer player should receive other amount of resource than computer (depending on difficulty)
  1089. std::vector<int> startres;
  1090. std::ifstream tis("config/startres.txt");
  1091. int k;
  1092. for (int j=0;j<scenarioOps->difficulty;j++)
  1093. {
  1094. tis >> k;
  1095. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1096. tis>>k;
  1097. }
  1098. tis >> k;
  1099. for (int i=0;i<RESOURCE_QUANTITY;i++)
  1100. {
  1101. tis >> k;
  1102. startres.push_back(k);
  1103. }
  1104. tis.close();
  1105. tis.clear();
  1106. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1107. {
  1108. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1109. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1110. (*i).second.resources[x] = startres[x];
  1111. }
  1112. tis.open("config/resources.txt");
  1113. tis >> k;
  1114. int pom;
  1115. for(int i=0;i<k;i++)
  1116. {
  1117. tis >> pom;
  1118. resVals.push_back(pom);
  1119. }
  1120. /*************************HEROES************************************************/
  1121. std::set<int> hids;
  1122. for(int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1123. if(map->allowedHeroes[i])
  1124. hids.insert(i);
  1125. for (int i=0; i<map->heroes.size();i++) //heroes instances
  1126. {
  1127. if (map->heroes[i]->getOwner()<0)
  1128. {
  1129. tlog2 << "Warning - hero with uninitialized owner!\n";
  1130. continue;
  1131. }
  1132. CGHeroInstance * vhi = (map->heroes[i]);
  1133. vhi->initHero();
  1134. players[vhi->getOwner()].heroes.push_back(vhi);
  1135. hids.erase(vhi->subID);
  1136. }
  1137. for(int i=0; i<map->predefinedHeroes.size(); i++)
  1138. {
  1139. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1140. continue;
  1141. map->predefinedHeroes[i]->initHero();
  1142. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1143. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1144. hids.erase(map->predefinedHeroes[i]->subID);
  1145. }
  1146. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go into the pool
  1147. {
  1148. CGHeroInstance * vhi = new CGHeroInstance();
  1149. vhi->initHero(hid);
  1150. hpool.heroesPool[hid] = vhi;
  1151. hpool.pavailable[hid] = 0xff;
  1152. }
  1153. for(int i=0; i<map->disposedHeroes.size(); i++)
  1154. {
  1155. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1156. }
  1157. /*************************FOG**OF**WAR******************************************/
  1158. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1159. {
  1160. k->second.fogOfWarMap.resize(map->width);
  1161. for(int g=0; g<map->width; ++g)
  1162. k->second.fogOfWarMap[g].resize(map->height);
  1163. for(int g=-0; g<map->width; ++g)
  1164. for(int h=0; h<map->height; ++h)
  1165. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1166. for(int g=0; g<map->width; ++g)
  1167. for(int h=0; h<map->height; ++h)
  1168. for(int v=0; v<map->twoLevel+1; ++v)
  1169. k->second.fogOfWarMap[g][h][v] = 0;
  1170. for(int xd=0; xd<map->width; ++xd) //revealing part of map around heroes
  1171. {
  1172. for(int yd=0; yd<map->height; ++yd)
  1173. {
  1174. for(int ch=0; ch<k->second.heroes.size(); ++ch)
  1175. {
  1176. int deltaX = (k->second.heroes[ch]->getPosition(false).x-xd)*(k->second.heroes[ch]->getPosition(false).x-xd);
  1177. int deltaY = (k->second.heroes[ch]->getPosition(false).y-yd)*(k->second.heroes[ch]->getPosition(false).y-yd);
  1178. if(deltaX+deltaY<k->second.heroes[ch]->getSightDistance()*k->second.heroes[ch]->getSightDistance())
  1179. k->second.fogOfWarMap[xd][yd][k->second.heroes[ch]->getPosition(false).z] = 1;
  1180. }
  1181. }
  1182. }
  1183. //starting bonus
  1184. if(si->playerInfos[k->second.serial].bonus==brandom)
  1185. si->playerInfos[k->second.serial].bonus = ran()%3;
  1186. switch(si->playerInfos[k->second.serial].bonus)
  1187. {
  1188. case bgold:
  1189. k->second.resources[6] += 500 + (ran()%6)*100;
  1190. break;
  1191. case bresource:
  1192. {
  1193. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1194. if(res == 127)
  1195. {
  1196. k->second.resources[0] += 5 + ran()%6;
  1197. k->second.resources[2] += 5 + ran()%6;
  1198. }
  1199. else
  1200. {
  1201. k->second.resources[res] += 3 + ran()%4;
  1202. }
  1203. break;
  1204. }
  1205. case bartifact:
  1206. {
  1207. if(!k->second.heroes.size())
  1208. {
  1209. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1210. break;
  1211. }
  1212. CArtifact *toGive;
  1213. do
  1214. {
  1215. toGive = VLC->arth->treasures[ran() % VLC->arth->treasures.size()];
  1216. } while (!map->allowedArtifact[toGive->id]);
  1217. CGHeroInstance *hero = k->second.heroes[0];
  1218. std::vector<ui16>::iterator slot = vstd::findFirstNot(hero->artifWorn,toGive->possibleSlots);
  1219. if(slot!=toGive->possibleSlots.end())
  1220. hero->artifWorn[*slot] = toGive->id;
  1221. else
  1222. hero->artifacts.push_back(toGive->id);
  1223. }
  1224. }
  1225. }
  1226. /****************************TOWNS************************************************/
  1227. for (int i=0;i<map->towns.size();i++)
  1228. {
  1229. CGTownInstance * vti =(map->towns[i]);
  1230. if(!vti->town)
  1231. vti->town = &VLC->townh->towns[vti->subID];
  1232. if (vti->name.length()==0) // if town hasn't name we draw it
  1233. vti->name=vti->town->names[ran()%vti->town->names.size()];
  1234. //init buildings
  1235. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1236. {
  1237. vti->builtBuildings.erase(-50);
  1238. vti->builtBuildings.insert(10);
  1239. vti->builtBuildings.insert(5);
  1240. vti->builtBuildings.insert(30);
  1241. if(ran()%2)
  1242. vti->builtBuildings.insert(31);
  1243. }
  1244. //init spells
  1245. vti->spells.resize(SPELL_LEVELS);
  1246. CSpell *s;
  1247. for(int z=0; z<vti->obligatorySpells.size();z++)
  1248. {
  1249. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1250. vti->spells[s->level-1].push_back(s->id);
  1251. vti->possibleSpells -= s->id;
  1252. }
  1253. while(vti->possibleSpells.size())
  1254. {
  1255. ui32 total=0, sel=-1;
  1256. for(int ps=0;ps<vti->possibleSpells.size();ps++)
  1257. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1258. int r = (total)? ran()%total : -1;
  1259. for(int ps=0; ps<vti->possibleSpells.size();ps++)
  1260. {
  1261. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1262. if(r<0)
  1263. {
  1264. sel = ps;
  1265. break;
  1266. }
  1267. }
  1268. if(sel<0)
  1269. sel=0;
  1270. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1271. vti->spells[s->level-1].push_back(s->id);
  1272. vti->possibleSpells -= s->id;
  1273. }
  1274. //init garrisons
  1275. for (std::map<si32,std::pair<ui32,si32> >::iterator j=vti->army.slots.begin(); j!=vti->army.slots.end();j++)
  1276. {
  1277. if(j->second.first > 196 && j->second.first < 211)
  1278. {
  1279. if(j->second.first%2)
  1280. j->second.first = vti->town->basicCreatures[ (j->second.first-197) / 2 ];
  1281. else
  1282. j->second.first = vti->town->upgradedCreatures[ (j->second.first-197) / 2 ];
  1283. }
  1284. }
  1285. players[vti->getOwner()].towns.push_back(vti);
  1286. }
  1287. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1288. {
  1289. if(k->first==-1 || k->first==255)
  1290. continue;
  1291. for(int xd=0; xd<map->width; ++xd) //revealing part of map around towns
  1292. {
  1293. for(int yd=0; yd<map->height; ++yd)
  1294. {
  1295. for(int ch=0; ch<k->second.towns.size(); ++ch)
  1296. {
  1297. int deltaX = (k->second.towns[ch]->pos.x-xd)*(k->second.towns[ch]->pos.x-xd);
  1298. int deltaY = (k->second.towns[ch]->pos.y-yd)*(k->second.towns[ch]->pos.y-yd);
  1299. if(deltaX+deltaY<k->second.towns[ch]->getSightDistance()*k->second.towns[ch]->getSightDistance())
  1300. k->second.fogOfWarMap[xd][yd][k->second.towns[ch]->pos.z] = 1;
  1301. }
  1302. }
  1303. }
  1304. //init visiting and garrisoned heroes
  1305. for(int l=0; l<k->second.heroes.size();l++)
  1306. {
  1307. for(int m=0; m<k->second.towns.size();m++)
  1308. {
  1309. int3 vistile = k->second.towns[m]->pos; vistile.x--; //tile next to the entrance
  1310. if(vistile == k->second.heroes[l]->pos || k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1311. {
  1312. k->second.towns[m]->visitingHero = k->second.heroes[l];
  1313. k->second.heroes[l]->visitedTown = k->second.towns[m];
  1314. k->second.heroes[l]->inTownGarrison = false;
  1315. if(k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1316. k->second.heroes[l]->pos.x -= 1;
  1317. break;
  1318. }
  1319. //else if(k->second.heroes[l]->pos == k->second.towns[m]->pos)
  1320. //{
  1321. // k->second.towns[m]->garrisonHero = k->second.heroes[l];
  1322. // k->second.towns[m]->army = k->second.heroes[l]->army;
  1323. // k->second.heroes[l]->visitedTown = k->second.towns[m];
  1324. // k->second.heroes[l]->inTownGarrison = true;
  1325. // k->second.heroes[l]->pos.x -= 1;
  1326. // goto mainplheloop;
  1327. //}
  1328. }
  1329. }
  1330. }
  1331. }
  1332. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1333. {
  1334. return true;
  1335. }
  1336. int CGameState::battleGetStack(int pos)
  1337. {
  1338. if(!curB)
  1339. return -1;
  1340. for(int g=0; g<curB->stacks.size(); ++g)
  1341. {
  1342. if(curB->stacks[g]->position == pos ||
  1343. ( curB->stacks[g]->creature->isDoubleWide() &&
  1344. ( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos) ||
  1345. (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos)
  1346. )
  1347. )
  1348. )
  1349. return curB->stacks[g]->ID;
  1350. }
  1351. return -1;
  1352. }
  1353. UpgradeInfo CGameState::getUpgradeInfo(CArmedInstance *obj, int stackPos)
  1354. {
  1355. UpgradeInfo ret;
  1356. CCreature *base = &VLC->creh->creatures[obj->army.slots[stackPos].first];
  1357. if((obj->ID == 98) || ((obj->ID == 34) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
  1358. {
  1359. CGTownInstance * t;
  1360. if(obj->ID == 98)
  1361. t = static_cast<CGTownInstance *>(const_cast<CArmedInstance *>(obj));
  1362. else
  1363. t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
  1364. for(std::set<si32>::iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++)
  1365. {
  1366. if( (*i) >= 37 && (*i) < 44 ) //upgraded creature dwelling
  1367. {
  1368. int nid = t->town->upgradedCreatures[(*i)-37]; //upgrade offered by that building
  1369. if(base->upgrades.find(nid) != base->upgrades.end()) //possible upgrade
  1370. {
  1371. ret.newID.push_back(nid);
  1372. ret.cost.push_back(std::set<std::pair<int,int> >());
  1373. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1374. {
  1375. int dif = VLC->creh->creatures[nid].cost[j] - base->cost[j];
  1376. if(dif)
  1377. ret.cost[ret.cost.size()-1].insert(std::make_pair(j,dif));
  1378. }
  1379. }
  1380. }
  1381. }//end for
  1382. }
  1383. //TODO: check if hero ability makes some upgrades possible
  1384. if(ret.newID.size())
  1385. ret.oldID = base->idNumber;
  1386. return ret;
  1387. }
  1388. float CGameState::getMarketEfficiency( int player, int mode/*=0*/ )
  1389. {
  1390. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1391. if(mode) return -1; //todo - support other modes
  1392. int mcount = 0;
  1393. for(int i=0;i<players[player].towns.size();i++)
  1394. if(vstd::contains(players[player].towns[i]->builtBuildings,14))
  1395. mcount++;
  1396. float ret = std::min(((float)mcount+1.0f)/20.0f,0.5f);
  1397. return ret;
  1398. }
  1399. std::set<int3> CGameState::tilesToReveal(int3 pos, int radious, int player)
  1400. {
  1401. std::set<int3> ret;
  1402. int xbeg = pos.x - radious - 2;
  1403. if(xbeg < 0)
  1404. xbeg = 0;
  1405. int xend = pos.x + radious + 2;
  1406. if(xend >= map->width)
  1407. xend = map->width;
  1408. int ybeg = pos.y - radious - 2;
  1409. if(ybeg < 0)
  1410. ybeg = 0;
  1411. int yend = pos.y + radious + 2;
  1412. if(yend >= map->height)
  1413. yend = map->height;
  1414. for(int xd=xbeg; xd<xend; ++xd) //revealing part of map around heroes
  1415. {
  1416. for(int yd=ybeg; yd<yend; ++yd)
  1417. {
  1418. int deltaX = (pos.x-xd)*(pos.x-xd);
  1419. int deltaY = (pos.y-yd)*(pos.y-yd);
  1420. if(deltaX+deltaY<radious*radious)
  1421. {
  1422. if(player<0 || players[player].fogOfWarMap[xd][yd][pos.z]==0)
  1423. {
  1424. ret.insert(int3(xd,yd,pos.z));
  1425. }
  1426. }
  1427. }
  1428. }
  1429. return ret;
  1430. }
  1431. int BattleInfo::calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting)
  1432. {
  1433. int attackDefenseBonus = attacker->creature->attack + (attackerHero ? attackerHero->getPrimSkillLevel(0) : 0) - (defender->creature->defence + (defendingHero ? defendingHero->getPrimSkillLevel(1) : 0));
  1434. int damageBase = 0;
  1435. if(attacker->creature->damageMax == attacker->creature->damageMin) //constant damage
  1436. {
  1437. damageBase = attacker->creature->damageMin;
  1438. }
  1439. else
  1440. {
  1441. damageBase = rand()%(attacker->creature->damageMax - attacker->creature->damageMin) + attacker->creature->damageMin + 1;
  1442. }
  1443. float dmgBonusMultiplier = 1.0f;
  1444. if(attackDefenseBonus < 0) //decreasing dmg
  1445. {
  1446. if(0.02f * (-attackDefenseBonus) > 0.3f)
  1447. {
  1448. dmgBonusMultiplier += -0.3f;
  1449. }
  1450. else
  1451. {
  1452. dmgBonusMultiplier += 0.02f * attackDefenseBonus;
  1453. }
  1454. }
  1455. else //increasing dmg
  1456. {
  1457. if(0.05f * attackDefenseBonus > 4.0f)
  1458. {
  1459. dmgBonusMultiplier += 4.0f;
  1460. }
  1461. else
  1462. {
  1463. dmgBonusMultiplier += 0.05f * attackDefenseBonus;
  1464. }
  1465. }
  1466. //handling secondary abilities
  1467. if(attackerHero)
  1468. {
  1469. if(shooting)
  1470. {
  1471. switch(attackerHero->getSecSkillLevel(1)) //archery
  1472. {
  1473. case 1: //basic
  1474. dmgBonusMultiplier *= 1.1f;
  1475. break;
  1476. case 2: //advanced
  1477. dmgBonusMultiplier *= 1.25f;
  1478. break;
  1479. case 3: //expert
  1480. dmgBonusMultiplier *= 1.5f;
  1481. break;
  1482. }
  1483. }
  1484. else
  1485. {
  1486. switch(attackerHero->getSecSkillLevel(22)) //offence
  1487. {
  1488. case 1: //basic
  1489. dmgBonusMultiplier *= 1.1f;
  1490. break;
  1491. case 2: //advanced
  1492. dmgBonusMultiplier *= 1.2f;
  1493. break;
  1494. case 3: //expert
  1495. dmgBonusMultiplier *= 1.3f;
  1496. break;
  1497. }
  1498. }
  1499. }
  1500. if(defendingHero)
  1501. {
  1502. switch(defendingHero->getSecSkillLevel(23)) //armourer
  1503. {
  1504. case 1: //basic
  1505. dmgBonusMultiplier *= 0.95f;
  1506. break;
  1507. case 2: //advanced
  1508. dmgBonusMultiplier *= 0.9f;
  1509. break;
  1510. case 3: //expert
  1511. dmgBonusMultiplier *= 0.85f;
  1512. break;
  1513. }
  1514. }
  1515. return (float)damageBase * (float)attacker->amount * dmgBonusMultiplier;
  1516. }
  1517. void BattleInfo::calculateCasualties( std::set<std::pair<ui32,si32> > *casualties )
  1518. {
  1519. for(int i=0; i<stacks.size();i++)//setting casualties
  1520. {
  1521. if(!stacks[i]->alive())
  1522. {
  1523. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount));
  1524. }
  1525. else if(stacks[i]->amount != stacks[i]->baseAmount)
  1526. {
  1527. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount - stacks[i]->amount));
  1528. }
  1529. }
  1530. }