CGameState.cpp 39 KB

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