CGameState.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322
  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. break;
  536. }
  537. case 3006:
  538. {
  539. BattleAttack *br = static_cast<BattleAttack*>(pack);
  540. applyNL(&br->bsa);
  541. break;
  542. }
  543. }
  544. }
  545. void CGameState::apply(IPack * pack)
  546. {
  547. while(!mx->try_lock())
  548. boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  549. applyNL(pack);
  550. mx->unlock();
  551. }
  552. int CGameState::pickHero(int owner)
  553. {
  554. int h=-1;
  555. if(!map->getHero(h = scenarioOps->getIthPlayersSettings(owner).hero,0) && h>=0) //we haven't used selected hero
  556. return h;
  557. int f = scenarioOps->getIthPlayersSettings(owner).castle;
  558. int i=0;
  559. do //try to find free hero of our faction
  560. {
  561. i++;
  562. h = scenarioOps->getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  563. } while( map->getHero(h) && i<175);
  564. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  565. {
  566. std::cout << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  567. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  568. if(!map->getHero(j))
  569. h=j;
  570. }
  571. return h;
  572. }
  573. CGHeroInstance *CGameState::getHero(int objid)
  574. {
  575. if(objid<0 || objid>=map->objects.size())
  576. return NULL;
  577. return static_cast<CGHeroInstance *>(map->objects[objid]);
  578. }
  579. CGTownInstance *CGameState::getTown(int objid)
  580. {
  581. if(objid<0 || objid>=map->objects.size())
  582. return NULL;
  583. return static_cast<CGTownInstance *>(map->objects[objid]);
  584. }
  585. std::pair<int,int> CGameState::pickObject(CGObjectInstance *obj)
  586. {
  587. switch(obj->ID)
  588. {
  589. case 65: //random artifact
  590. return std::pair<int,int>(5,(ran()%136)+7); //tylko sensowny zakres - na poczatku sa katapulty itp, na koncu specjalne i blanki
  591. case 66: //random treasure artifact
  592. return std::pair<int,int>(5,VLC->arth->treasures[ran()%VLC->arth->treasures.size()]->id);
  593. case 67: //random minor artifact
  594. return std::pair<int,int>(5,VLC->arth->minors[ran()%VLC->arth->minors.size()]->id);
  595. case 68: //random major artifact
  596. return std::pair<int,int>(5,VLC->arth->majors[ran()%VLC->arth->majors.size()]->id);
  597. case 69: //random relic artifact
  598. return std::pair<int,int>(5,VLC->arth->relics[ran()%VLC->arth->relics.size()]->id);
  599. case 70: //random hero
  600. {
  601. return std::pair<int,int>(34,pickHero(obj->tempOwner));
  602. }
  603. case 71: //random monster
  604. {
  605. int r;
  606. do
  607. {
  608. r = ran()%197;
  609. } while (vstd::contains(VLC->creh->notUsedMonsters,r));
  610. return std::pair<int,int>(54,r);
  611. }
  612. case 72: //random monster lvl1
  613. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  614. case 73: //random monster lvl2
  615. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  616. case 74: //random monster lvl3
  617. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  618. case 75: //random monster lvl4
  619. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  620. case 76: //random resource
  621. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  622. case 77: //random town
  623. {
  624. int align = ((CGTownInstance*)obj)->alignment,
  625. f;
  626. if(align>PLAYER_LIMIT-1)//same as owner / random
  627. {
  628. if(obj->tempOwner > PLAYER_LIMIT-1)
  629. f = -1; //random
  630. else
  631. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  632. }
  633. else
  634. {
  635. f = scenarioOps->getIthPlayersSettings(align).castle;
  636. }
  637. if(f<0) f = ran()%VLC->townh->towns.size();
  638. return std::pair<int,int>(98,f);
  639. }
  640. case 162: //random monster lvl5
  641. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  642. case 163: //random monster lvl6
  643. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  644. case 164: //random monster lvl7
  645. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  646. case 216: //random dwelling
  647. {
  648. int faction = ran()%F_NUMBER;
  649. CCreGen2ObjInfo* info =(CCreGen2ObjInfo*)obj->info;
  650. if (info->asCastle)
  651. {
  652. for(int i=0;i<map->objects.size();i++)
  653. {
  654. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  655. {
  656. randomizeObject(map->objects[i]); //we have to randomize the castle first
  657. faction = map->objects[i]->subID;
  658. break;
  659. }
  660. else if(map->objects[i]->ID==98 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  661. {
  662. faction = map->objects[i]->subID;
  663. break;
  664. }
  665. }
  666. }
  667. else
  668. {
  669. while((!(info->castles[0]&(1<<faction))))
  670. {
  671. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  672. break;
  673. faction = ran()%F_NUMBER;
  674. }
  675. }
  676. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  677. int cid = VLC->townh->towns[faction].basicCreatures[level];
  678. for(int i=0;i<VLC->objh->cregens.size();i++)
  679. if(VLC->objh->cregens[i]==cid)
  680. return std::pair<int,int>(17,i);
  681. std::cout << "Cannot find a dwelling for creature "<<cid <<std::endl;
  682. return std::pair<int,int>(17,0);
  683. }
  684. case 217:
  685. {
  686. int faction = ran()%F_NUMBER;
  687. CCreGenObjInfo* info =(CCreGenObjInfo*)obj->info;
  688. if (info->asCastle)
  689. {
  690. for(int i=0;i<map->objects.size();i++)
  691. {
  692. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  693. {
  694. randomizeObject(map->objects[i]); //we have to randomize the castle first
  695. faction = map->objects[i]->subID;
  696. break;
  697. }
  698. else if(map->objects[i]->ID==98 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  699. {
  700. faction = map->objects[i]->subID;
  701. break;
  702. }
  703. }
  704. }
  705. else
  706. {
  707. while((!(info->castles[0]&(1<<faction))))
  708. {
  709. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  710. break;
  711. faction = ran()%F_NUMBER;
  712. }
  713. }
  714. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  715. for(int i=0;i<VLC->objh->cregens.size();i++)
  716. if(VLC->objh->cregens[i]==cid)
  717. return std::pair<int,int>(17,i);
  718. std::cout << "Cannot find a dwelling for creature "<<cid <<std::endl;
  719. return std::pair<int,int>(17,0);
  720. }
  721. case 218:
  722. {
  723. CCreGen3ObjInfo* info =(CCreGen3ObjInfo*)obj->info;
  724. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  725. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  726. for(int i=0;i<VLC->objh->cregens.size();i++)
  727. if(VLC->objh->cregens[i]==cid)
  728. return std::pair<int,int>(17,i);
  729. std::cout << "Cannot find a dwelling for creature "<<cid <<std::endl;
  730. return std::pair<int,int>(17,0);
  731. }
  732. }
  733. return std::pair<int,int>(-1,-1);
  734. }
  735. void CGameState::randomizeObject(CGObjectInstance *cur)
  736. {
  737. std::pair<int,int> ran = pickObject(cur);
  738. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  739. {
  740. if(cur->ID==98) //town - set def
  741. {
  742. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  743. if(t->hasCapitol())
  744. t->defInfo = capitols[t->subID];
  745. else if(t->hasFort())
  746. t->defInfo = forts[t->subID];
  747. else
  748. t->defInfo = villages[t->subID];
  749. }
  750. return;
  751. }
  752. else if(ran.first==34)//special code for hero
  753. {
  754. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  755. if(!h) {std::cout<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  756. cur->ID = ran.first;
  757. h->portrait = cur->subID = ran.second;
  758. h->type = VLC->heroh->heroes[ran.second];
  759. map->heroes.push_back(h);
  760. return; //TODO: maybe we should do something with definfo?
  761. }
  762. else if(ran.first==98)//special code for town
  763. {
  764. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  765. if(!t) {std::cout<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  766. cur->ID = ran.first;
  767. cur->subID = ran.second;
  768. t->town = &VLC->townh->towns[ran.second];
  769. if(t->hasCapitol())
  770. t->defInfo = capitols[t->subID];
  771. else if(t->hasFort())
  772. t->defInfo = forts[t->subID];
  773. else
  774. t->defInfo = villages[t->subID];
  775. map->towns.push_back(t);
  776. return;
  777. }
  778. //we have to replace normal random object
  779. cur->ID = ran.first;
  780. cur->subID = ran.second;
  781. map->defs.insert(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  782. if(!cur->defInfo)
  783. {
  784. std::cout<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  785. return;
  786. }
  787. }
  788. int CGameState::getDate(int mode) const
  789. {
  790. int temp;
  791. switch (mode)
  792. {
  793. case 0:
  794. return day;
  795. break;
  796. case 1:
  797. temp = (day)%7;
  798. if (temp)
  799. return temp;
  800. else return 7;
  801. break;
  802. case 2:
  803. temp = ((day-1)/7)+1;
  804. if (!(temp%4))
  805. return 4;
  806. else
  807. return (temp%4);
  808. break;
  809. case 3:
  810. return ((day-1)/28)+1;
  811. break;
  812. }
  813. return 0;
  814. }
  815. CGameState::CGameState()
  816. {
  817. mx = new boost::shared_mutex();
  818. }
  819. CGameState::~CGameState()
  820. {
  821. delete mx;
  822. }
  823. void CGameState::init(StartInfo * si, Mapa * map, int Seed)
  824. {
  825. day = 0;
  826. seed = Seed;
  827. ran.seed((boost::int32_t)seed);
  828. scenarioOps = si;
  829. this->map = map;
  830. for(int i=0;i<F_NUMBER;i++)
  831. {
  832. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  833. forts[i] = VLC->dobjinfo->castles[i];
  834. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  835. }
  836. //picking random factions for players
  837. for(int i=0;i<scenarioOps->playerInfos.size();i++)
  838. {
  839. if(scenarioOps->playerInfos[i].castle==-1)
  840. {
  841. int f;
  842. do
  843. {
  844. f = ran()%F_NUMBER;
  845. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  846. scenarioOps->playerInfos[i].castle = f;
  847. }
  848. }
  849. //randomizing objects
  850. for(int no=0; no<map->objects.size(); ++no)
  851. {
  852. randomizeObject(map->objects[no]);
  853. if(map->objects[no]->ID==26)
  854. map->objects[no]->defInfo->handler=NULL;
  855. map->objects[no]->hoverName = VLC->objh->names[map->objects[no]->ID];
  856. }
  857. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  858. /*********give starting hero****************************************/
  859. for(int i=0;i<PLAYER_LIMIT;i++)
  860. {
  861. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==RoE))
  862. {
  863. int3 hpos = map->players[i].posOfMainTown;
  864. hpos.x+=1;// hpos.y+=1;
  865. int j;
  866. for(j=0; j<scenarioOps->playerInfos.size(); j++)
  867. if(scenarioOps->playerInfos[j].color == i)
  868. break;
  869. if(j == scenarioOps->playerInfos.size())
  870. continue;
  871. int h=pickHero(i);
  872. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(34,h,hpos,i));
  873. nnn->id = map->objects.size();
  874. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  875. for(int o=0;o<map->towns.size();o++) //find main town
  876. {
  877. if(map->towns[o]->pos == hpos)
  878. {
  879. map->towns[o]->visitingHero = nnn;
  880. nnn->visitedTown = map->towns[o];
  881. nnn->inTownGarrison = false;
  882. break;
  883. }
  884. }
  885. map->heroes.push_back(nnn);
  886. map->objects.push_back(nnn);
  887. }
  888. }
  889. /*********creating players entries in gs****************************************/
  890. for (int i=0; i<scenarioOps->playerInfos.size();i++)
  891. {
  892. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  893. ins.second.color=ins.first;
  894. ins.second.serial=i;
  895. players.insert(ins);
  896. }
  897. /******************RESOURCES****************************************************/
  898. //TODO: computer player should receive other amount of resource than computer (depending on difficulty)
  899. std::vector<int> startres;
  900. std::ifstream tis("config/startres.txt");
  901. int k;
  902. for (int j=0;j<scenarioOps->difficulty;j++)
  903. {
  904. tis >> k;
  905. for (int z=0;z<RESOURCE_QUANTITY;z++)
  906. tis>>k;
  907. }
  908. tis >> k;
  909. for (int i=0;i<RESOURCE_QUANTITY;i++)
  910. {
  911. tis >> k;
  912. startres.push_back(k);
  913. }
  914. tis.close();
  915. tis.clear();
  916. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  917. {
  918. (*i).second.resources.resize(RESOURCE_QUANTITY);
  919. for (int x=0;x<RESOURCE_QUANTITY;x++)
  920. (*i).second.resources[x] = startres[x];
  921. }
  922. tis.open("config/resources.txt");
  923. tis >> k;
  924. int pom;
  925. for(int i=0;i<k;i++)
  926. {
  927. tis >> pom;
  928. resVals.push_back(pom);
  929. }
  930. /*************************HEROES************************************************/
  931. for (int i=0; i<map->heroes.size();i++) //heroes instances
  932. {
  933. if (map->heroes[i]->getOwner()<0)
  934. continue;
  935. CGHeroInstance * vhi = (map->heroes[i]);
  936. if(!vhi->type)
  937. vhi->type = VLC->heroh->heroes[vhi->subID];
  938. if (vhi->level<1)
  939. {
  940. vhi->exp=40+ran()%50;
  941. vhi->level = 1;
  942. }
  943. if (vhi->level>1) ;//TODO dodac um dr, ale potrzebne los
  944. if ((!vhi->primSkills.size()) || (vhi->primSkills[0]<0))
  945. {
  946. if (vhi->primSkills.size()<PRIMARY_SKILLS)
  947. vhi->primSkills.resize(PRIMARY_SKILLS);
  948. vhi->primSkills[0] = vhi->type->heroClass->initialAttack;
  949. vhi->primSkills[1] = vhi->type->heroClass->initialDefence;
  950. vhi->primSkills[2] = vhi->type->heroClass->initialPower;
  951. vhi->primSkills[3] = vhi->type->heroClass->initialKnowledge;
  952. }
  953. vhi->mana = vhi->primSkills[3]*10;
  954. if (!vhi->name.length())
  955. {
  956. vhi->name = vhi->type->name;
  957. }
  958. if (!vhi->biography.length())
  959. {
  960. vhi->biography = vhi->type->biography;
  961. }
  962. if (vhi->portrait < 0)
  963. vhi->portrait = vhi->type->ID;
  964. vhi->artifWorn[16] = 3;
  965. //initial army
  966. if (!vhi->army.slots.size()) //standard army
  967. {
  968. int pom, pom2=0;
  969. for(int x=0;x<3;x++)
  970. {
  971. pom = (VLC->creh->nameToID[vhi->type->refTypeStack[x]]);
  972. if(pom>=145 && pom<=149) //war machine
  973. {
  974. pom2++;
  975. switch (pom)
  976. {
  977. case 145: //catapult
  978. vhi->artifWorn[16] = 3;
  979. break;
  980. default:
  981. vhi->artifWorn[9+CArtHandler::convertMachineID(pom,true)] = CArtHandler::convertMachineID(pom,true);
  982. break;
  983. }
  984. continue;
  985. }
  986. vhi->army.slots[x-pom2].first = pom;
  987. if((pom = (vhi->type->highStack[x]-vhi->type->lowStack[x])) > 0)
  988. vhi->army.slots[x-pom2].second = (ran()%pom)+vhi->type->lowStack[x];
  989. else
  990. vhi->army.slots[x-pom2].second = +vhi->type->lowStack[x];
  991. }
  992. }
  993. players[vhi->getOwner()].heroes.push_back(vhi);
  994. }
  995. /*************************FOG**OF**WAR******************************************/
  996. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  997. {
  998. k->second.fogOfWarMap.resize(map->width);
  999. for(int g=0; g<map->width; ++g)
  1000. k->second.fogOfWarMap[g].resize(map->height);
  1001. for(int g=-0; g<map->width; ++g)
  1002. for(int h=0; h<map->height; ++h)
  1003. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1004. for(int g=0; g<map->width; ++g)
  1005. for(int h=0; h<map->height; ++h)
  1006. for(int v=0; v<map->twoLevel+1; ++v)
  1007. k->second.fogOfWarMap[g][h][v] = 0;
  1008. for(int xd=0; xd<map->width; ++xd) //revealing part of map around heroes
  1009. {
  1010. for(int yd=0; yd<map->height; ++yd)
  1011. {
  1012. for(int ch=0; ch<k->second.heroes.size(); ++ch)
  1013. {
  1014. int deltaX = (k->second.heroes[ch]->getPosition(false).x-xd)*(k->second.heroes[ch]->getPosition(false).x-xd);
  1015. int deltaY = (k->second.heroes[ch]->getPosition(false).y-yd)*(k->second.heroes[ch]->getPosition(false).y-yd);
  1016. if(deltaX+deltaY<k->second.heroes[ch]->getSightDistance()*k->second.heroes[ch]->getSightDistance())
  1017. k->second.fogOfWarMap[xd][yd][k->second.heroes[ch]->getPosition(false).z] = 1;
  1018. }
  1019. }
  1020. }
  1021. //starting bonus
  1022. if(si->playerInfos[k->second.serial].bonus==brandom)
  1023. si->playerInfos[k->second.serial].bonus = ran()%3;
  1024. switch(si->playerInfos[k->second.serial].bonus)
  1025. {
  1026. case bgold:
  1027. k->second.resources[6] += 500 + (ran()%6)*100;
  1028. break;
  1029. case bresource:
  1030. {
  1031. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1032. if(res == 127)
  1033. {
  1034. k->second.resources[0] += 5 + ran()%6;
  1035. k->second.resources[2] += 5 + ran()%6;
  1036. }
  1037. else
  1038. {
  1039. k->second.resources[res] += 3 + ran()%4;
  1040. }
  1041. break;
  1042. }
  1043. case bartifact:
  1044. {
  1045. if(!k->second.heroes.size())
  1046. {
  1047. std::cout << "Cannot give starting artifact - no heroes!" << std::endl;
  1048. break;
  1049. }
  1050. CArtifact *toGive;
  1051. do
  1052. {
  1053. toGive = VLC->arth->treasures[ran() % VLC->arth->treasures.size()];
  1054. } while (!map->allowedArtifact[toGive->id]);
  1055. CGHeroInstance *hero = k->second.heroes[0];
  1056. std::vector<ui16>::iterator slot = vstd::findFirstNot(hero->artifWorn,toGive->possibleSlots);
  1057. if(slot!=toGive->possibleSlots.end())
  1058. hero->artifWorn[*slot] = toGive->id;
  1059. else
  1060. hero->artifacts.push_back(toGive->id);
  1061. }
  1062. }
  1063. }
  1064. /****************************TOWNS************************************************/
  1065. for (int i=0;i<map->towns.size();i++)
  1066. {
  1067. CGTownInstance * vti =(map->towns[i]);
  1068. if(!vti->town)
  1069. vti->town = &VLC->townh->towns[vti->subID];
  1070. if (vti->name.length()==0) // if town hasn't name we draw it
  1071. vti->name=vti->town->names[ran()%vti->town->names.size()];
  1072. //init buildings
  1073. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1074. {
  1075. vti->builtBuildings.erase(-50);
  1076. vti->builtBuildings.insert(10);
  1077. vti->builtBuildings.insert(5);
  1078. vti->builtBuildings.insert(30);
  1079. if(ran()%2)
  1080. vti->builtBuildings.insert(31);
  1081. }
  1082. //init spells
  1083. vti->spells.resize(SPELL_LEVELS);
  1084. CSpell *s;
  1085. for(int z=0; z<vti->obligatorySpells.size();z++)
  1086. {
  1087. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1088. vti->spells[s->level-1].push_back(s->id);
  1089. vti->possibleSpells -= s->id;
  1090. }
  1091. while(vti->possibleSpells.size())
  1092. {
  1093. ui32 total=0, sel=-1;
  1094. for(int ps=0;ps<vti->possibleSpells.size();ps++)
  1095. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1096. int r = (total)? ran()%total : -1;
  1097. for(int ps=0; ps<vti->possibleSpells.size();ps++)
  1098. {
  1099. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1100. if(r<0)
  1101. {
  1102. sel = ps;
  1103. break;
  1104. }
  1105. }
  1106. if(sel<0)
  1107. sel=0;
  1108. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1109. vti->spells[s->level-1].push_back(s->id);
  1110. vti->possibleSpells -= s->id;
  1111. }
  1112. //init garrisons
  1113. for (std::map<si32,std::pair<ui32,si32> >::iterator j=vti->army.slots.begin(); j!=vti->army.slots.end();j++)
  1114. {
  1115. if(j->second.first > 196 && j->second.first < 211)
  1116. {
  1117. if(j->second.first%2)
  1118. j->second.first = vti->town->basicCreatures[ (j->second.first-197) / 2 ];
  1119. else
  1120. j->second.first = vti->town->upgradedCreatures[ (j->second.first-197) / 2 ];
  1121. }
  1122. }
  1123. players[vti->getOwner()].towns.push_back(vti);
  1124. }
  1125. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1126. {
  1127. if(k->first==-1 || k->first==255)
  1128. continue;
  1129. for(int xd=0; xd<map->width; ++xd) //revealing part of map around towns
  1130. {
  1131. for(int yd=0; yd<map->height; ++yd)
  1132. {
  1133. for(int ch=0; ch<k->second.towns.size(); ++ch)
  1134. {
  1135. int deltaX = (k->second.towns[ch]->pos.x-xd)*(k->second.towns[ch]->pos.x-xd);
  1136. int deltaY = (k->second.towns[ch]->pos.y-yd)*(k->second.towns[ch]->pos.y-yd);
  1137. if(deltaX+deltaY<k->second.towns[ch]->getSightDistance()*k->second.towns[ch]->getSightDistance())
  1138. k->second.fogOfWarMap[xd][yd][k->second.towns[ch]->pos.z] = 1;
  1139. }
  1140. }
  1141. }
  1142. //init visiting and garrisoned heroes
  1143. for(int l=0; l<k->second.heroes.size();l++)
  1144. {
  1145. for(int m=0; m<k->second.towns.size();m++)
  1146. {
  1147. int3 vistile = k->second.towns[m]->pos; vistile.x--; //tile next to the entrance
  1148. if(vistile == k->second.heroes[l]->pos || k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1149. {
  1150. k->second.towns[m]->visitingHero = k->second.heroes[l];
  1151. k->second.heroes[l]->visitedTown = k->second.towns[m];
  1152. k->second.heroes[l]->inTownGarrison = false;
  1153. if(k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1154. k->second.heroes[l]->pos.x -= 1;
  1155. break;
  1156. }
  1157. //else if(k->second.heroes[l]->pos == k->second.towns[m]->pos)
  1158. //{
  1159. // k->second.towns[m]->garrisonHero = k->second.heroes[l];
  1160. // k->second.towns[m]->army = k->second.heroes[l]->army;
  1161. // k->second.heroes[l]->visitedTown = k->second.towns[m];
  1162. // k->second.heroes[l]->inTownGarrison = true;
  1163. // k->second.heroes[l]->pos.x -= 1;
  1164. // goto mainplheloop;
  1165. //}
  1166. }
  1167. }
  1168. }
  1169. }
  1170. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1171. {
  1172. return true;
  1173. }
  1174. int CGameState::battleGetStack(int pos)
  1175. {
  1176. if(!curB)
  1177. return -1;
  1178. for(int g=0; g<curB->stacks.size(); ++g)
  1179. {
  1180. if(curB->stacks[g]->position == pos ||
  1181. ( curB->stacks[g]->creature->isDoubleWide() &&
  1182. ( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos) ||
  1183. (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos)
  1184. )
  1185. )
  1186. )
  1187. return curB->stacks[g]->ID;
  1188. }
  1189. return -1;
  1190. }
  1191. UpgradeInfo CGameState::getUpgradeInfo(CArmedInstance *obj, int stackPos)
  1192. {
  1193. UpgradeInfo ret;
  1194. CCreature *base = &VLC->creh->creatures[obj->army.slots[stackPos].first];
  1195. if((obj->ID == 98) || ((obj->ID == 34) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
  1196. {
  1197. CGTownInstance * t;
  1198. if(obj->ID == 98)
  1199. t = static_cast<CGTownInstance *>(const_cast<CArmedInstance *>(obj));
  1200. else
  1201. t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
  1202. for(std::set<si32>::iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++)
  1203. {
  1204. if( (*i) >= 37 && (*i) < 44 ) //upgraded creature dwelling
  1205. {
  1206. int nid = t->town->upgradedCreatures[(*i)-37]; //upgrade offered by that building
  1207. if(base->upgrades.find(nid) != base->upgrades.end()) //possible upgrade
  1208. {
  1209. ret.newID.push_back(nid);
  1210. ret.cost.push_back(std::set<std::pair<int,int> >());
  1211. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1212. {
  1213. int dif = VLC->creh->creatures[nid].cost[j] - base->cost[j];
  1214. if(dif)
  1215. ret.cost[ret.cost.size()-1].insert(std::make_pair(j,dif));
  1216. }
  1217. }
  1218. }
  1219. }//end for
  1220. }
  1221. //TODO: check if hero ability makes some upgrades possible
  1222. if(ret.newID.size())
  1223. ret.oldID = base->idNumber;
  1224. return ret;
  1225. }
  1226. float CGameState::getMarketEfficiency( int player, int mode/*=0*/ )
  1227. {
  1228. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1229. if(mode) return -1; //todo - support other modes
  1230. int mcount = 0;
  1231. for(int i=0;i<players[player].towns.size();i++)
  1232. if(vstd::contains(players[player].towns[i]->builtBuildings,14))
  1233. mcount++;
  1234. float ret = std::min(((float)mcount+1.0f)/20.0f,0.5f);
  1235. return ret;
  1236. }
  1237. int BattleInfo::calculateDmg(const CStack* attacker, const CStack* defender)
  1238. {
  1239. int attackDefenseBonus = attacker->creature->attack - defender->creature->defence;
  1240. int damageBase = 0;
  1241. if(attacker->creature->damageMax == attacker->creature->damageMin) //constant damage
  1242. {
  1243. damageBase = attacker->creature->damageMin;
  1244. }
  1245. else
  1246. {
  1247. damageBase = rand()%(attacker->creature->damageMax - attacker->creature->damageMin) + attacker->creature->damageMin + 1;
  1248. }
  1249. float dmgBonusMultiplier = 1.0;
  1250. if(attackDefenseBonus < 0) //decreasing dmg
  1251. {
  1252. if(0.02f * (-attackDefenseBonus) > 0.3f)
  1253. {
  1254. dmgBonusMultiplier += -0.3f;
  1255. }
  1256. else
  1257. {
  1258. dmgBonusMultiplier += 0.02f * attackDefenseBonus;
  1259. }
  1260. }
  1261. else //increasing dmg
  1262. {
  1263. if(0.05f * attackDefenseBonus > 4.0f)
  1264. {
  1265. dmgBonusMultiplier += 4.0f;
  1266. }
  1267. else
  1268. {
  1269. dmgBonusMultiplier += 0.05f * attackDefenseBonus;
  1270. }
  1271. }
  1272. return (float)damageBase * (float)attacker->amount * dmgBonusMultiplier;
  1273. }