CGameState.cpp 40 KB

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