CGameState.cpp 39 KB

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