CGameState.cpp 33 KB

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