CGameState.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758
  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 = new CGHeroInstance();
  36. nobj->pos = pos;
  37. nobj->tempOwner = owner;
  38. nobj->subID = subid;
  39. //nobj->initHero(ran);
  40. return nobj;
  41. }
  42. case 98: //town
  43. nobj = new CGTownInstance;
  44. break;
  45. default: //rest of objects
  46. nobj = new CGObjectInstance;
  47. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  48. break;
  49. }
  50. nobj->ID = id;
  51. nobj->subID = subid;
  52. if(!nobj->defInfo)
  53. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  54. nobj->pos = pos;
  55. //nobj->state = NULL;//new CLuaObjectScript();
  56. nobj->tempOwner = owner;
  57. nobj->info = NULL;
  58. nobj->defInfo->id = id;
  59. nobj->defInfo->subid = subid;
  60. //assigning defhandler
  61. if(nobj->ID==34 || nobj->ID==98)
  62. return nobj;
  63. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  64. return nobj;
  65. }
  66. CStack * BattleInfo::getStack(int stackID)
  67. {
  68. for(int g=0; g<stacks.size(); ++g)
  69. {
  70. if(stacks[g]->ID == stackID)
  71. return stacks[g];
  72. }
  73. return NULL;
  74. }
  75. CStack * BattleInfo::getStackT(int tileID)
  76. {
  77. for(int g=0; g<stacks.size(); ++g)
  78. {
  79. if(stacks[g]->position == tileID
  80. || (stacks[g]->creature->isDoubleWide() && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  81. || (stacks[g]->creature->isDoubleWide() && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  82. {
  83. if(stacks[g]->alive())
  84. {
  85. return stacks[g];
  86. }
  87. }
  88. }
  89. return NULL;
  90. }
  91. void BattleInfo::getAccessibilityMap(bool *accessibility, int stackToOmmit)
  92. {
  93. memset(accessibility,1,BFIELD_SIZE); //initialize array with trues
  94. for(int g=0; g<stacks.size(); ++g)
  95. {
  96. if(!stacks[g]->alive() || stacks[g]->ID==stackToOmmit) //we don't want to lock position of this stack
  97. continue;
  98. accessibility[stacks[g]->position] = false;
  99. if(stacks[g]->creature->isDoubleWide()) //if it's a double hex creature
  100. {
  101. if(stacks[g]->attackerOwned)
  102. accessibility[stacks[g]->position-1] = false;
  103. else
  104. accessibility[stacks[g]->position+1] = false;
  105. }
  106. }
  107. //TODO: obstacles
  108. }
  109. void BattleInfo::getAccessibilityMapForTwoHex(bool *accessibility, bool atackerSide, int stackToOmmit) //send pointer to at least 187 allocated bytes
  110. {
  111. bool mac[BFIELD_SIZE];
  112. getAccessibilityMap(mac,stackToOmmit);
  113. memcpy(accessibility,mac,BFIELD_SIZE);
  114. for(int b=0; b<BFIELD_SIZE; ++b)
  115. {
  116. if( mac[b] && !(atackerSide ? mac[b-1] : mac[b+1]))
  117. {
  118. accessibility[b] = false;
  119. }
  120. }
  121. //removing accessibility for side hexes
  122. for(int v=0; v<BFIELD_SIZE; ++v)
  123. if(atackerSide ? (v%17)==1 : (v%17)==15)
  124. accessibility[v] = false;
  125. }
  126. void BattleInfo::makeBFS(int start, bool*accessibility, int *predecessor, int *dists) //both pointers must point to the at least 187-elements int arrays
  127. {
  128. //inits
  129. for(int b=0; b<BFIELD_SIZE; ++b)
  130. predecessor[b] = -1;
  131. for(int g=0; g<BFIELD_SIZE; ++g)
  132. dists[g] = 100000000;
  133. std::queue<int> hexq; //bfs queue
  134. hexq.push(start);
  135. dists[hexq.front()] = 0;
  136. int curNext = -1; //for bfs loop only (helper var)
  137. while(!hexq.empty()) //bfs loop
  138. {
  139. int curHex = hexq.front();
  140. std::vector<int> neighbours = neighbouringTiles(curHex);
  141. hexq.pop();
  142. for(int nr=0; nr<neighbours.size(); nr++)
  143. {
  144. curNext = neighbours[nr];
  145. if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  146. continue;
  147. hexq.push(curNext);
  148. dists[curNext] = dists[curHex] + 1;
  149. predecessor[curNext] = curHex;
  150. }
  151. }
  152. };
  153. std::vector<int> BattleInfo::getAccessibility(int stackID)
  154. {
  155. std::vector<int> ret;
  156. bool ac[BFIELD_SIZE];
  157. CStack *s = getStack(stackID);
  158. if(s->creature->isDoubleWide())
  159. getAccessibilityMapForTwoHex(ac,s->attackerOwned,stackID);
  160. else
  161. getAccessibilityMap(ac,stackID);
  162. int pr[BFIELD_SIZE], dist[BFIELD_SIZE];
  163. makeBFS(s->position,ac,pr,dist);
  164. for(int i=0;i<BFIELD_SIZE;i++)
  165. if(dist[i] <= s->speed())
  166. ret.push_back(i);
  167. return ret;
  168. }
  169. bool BattleInfo::isStackBlocked(int ID)
  170. {
  171. CStack *our = getStack(ID);
  172. for(int i=0; i<stacks.size();i++)
  173. {
  174. if( !stacks[i]->alive()
  175. || stacks[i]->owner==our->owner
  176. )
  177. continue; //we omit dead and allied stacks
  178. if(stacks[i]->creature->isDoubleWide())
  179. {
  180. if( mutualPosition(stacks[i]->position, our->position) >= 0
  181. || mutualPosition(stacks[i]->position + (stacks[i]->attackerOwned ? -1 : 1), our->position) >= 0)
  182. return true;
  183. }
  184. else
  185. {
  186. if( mutualPosition(stacks[i]->position, our->position) >= 0 )
  187. return true;
  188. }
  189. }
  190. return false;
  191. }
  192. signed char BattleInfo::mutualPosition(int hex1, int hex2)
  193. {
  194. if(hex2 == hex1 - ( (hex1/17)%2 ? 18 : 17 )) //top left
  195. return 0;
  196. if(hex2 == hex1 - ( (hex1/17)%2 ? 17 : 16 )) //top right
  197. return 1;
  198. if(hex2 == hex1 - 1 && hex1%17 != 0) //left
  199. return 5;
  200. if(hex2 == hex1 + 1 && hex1%17 != 16) //right
  201. return 2;
  202. if(hex2 == hex1 + ( (hex1/17)%2 ? 16 : 17 )) //bottom left
  203. return 4;
  204. if(hex2 == hex1 + ( (hex1/17)%2 ? 17 : 18 )) //bottom right
  205. return 3;
  206. return -1;
  207. }
  208. std::vector<int> BattleInfo::neighbouringTiles(int hex)
  209. {
  210. #define CHECK_AND_PUSH(tile) {int hlp = (tile); if(hlp>=0 && hlp<BFIELD_SIZE && (hlp%BFIELD_WIDTH!=16) && hlp%BFIELD_WIDTH) ret.push_back(hlp);}
  211. std::vector<int> ret;
  212. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 18 : 17 ));
  213. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 17 : 16 ));
  214. CHECK_AND_PUSH(hex - 1);
  215. CHECK_AND_PUSH(hex + 1);
  216. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 16 : 17 ));
  217. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 17 : 18 ));
  218. #undef CHECK_AND_PUSH
  219. return ret;
  220. }
  221. std::vector<int> BattleInfo::getPath(int start, int dest, bool*accessibility)
  222. {
  223. int predecessor[BFIELD_SIZE]; //for getting the Path
  224. int dist[BFIELD_SIZE]; //calculated distances
  225. makeBFS(start,accessibility,predecessor,dist);
  226. //making the Path
  227. std::vector<int> path;
  228. int curElem = dest;
  229. while(curElem != start)
  230. {
  231. path.push_back(curElem);
  232. curElem = predecessor[curElem];
  233. }
  234. return path;
  235. }
  236. CStack::CStack(CCreature * C, int A, int O, int I, bool AO, int S)
  237. :creature(C),amount(A), baseAmount(A), owner(O), position(-1), ID(I), attackerOwned(AO), firstHPleft(C->hitPoints),
  238. shots(C->shots), slot(S), counterAttacks(1), effects(), state()
  239. {
  240. abilities = C->abilities;
  241. state.insert(ALIVE);
  242. }
  243. ui32 CStack::speed() const
  244. {
  245. int premy=0;
  246. const StackEffect *effect = 0;
  247. //haste effect check
  248. effect = getEffect(53);
  249. if(effect)
  250. premy += VLC->spellh->spells[effect->id].powers[effect->level];
  251. //slow effect check
  252. effect = getEffect(54);
  253. if(effect)
  254. premy -= VLC->spellh->spells[effect->id].powers[effect->level];
  255. //prayer effect check
  256. effect = getEffect(48);
  257. if(effect)
  258. premy += VLC->spellh->spells[effect->id].powers[effect->level];
  259. //bind effect check
  260. effect = getEffect(72);
  261. if(effect)
  262. premy = -creature->speed;
  263. return creature->speed + premy;
  264. }
  265. const CStack::StackEffect * CStack::getEffect(ui16 id) const
  266. {
  267. for (int i=0; i< effects.size(); i++)
  268. if(effects[i].id == id)
  269. return &effects[i];
  270. return NULL;
  271. }
  272. CGHeroInstance* CGameState::HeroesPool::pickHeroFor(bool native, int player, const CTown *town, int notThatOne)
  273. {
  274. if(player<0 || player>=PLAYER_LIMIT)
  275. {
  276. tlog1 << "Cannot pick hero for " << town->Name() << ". Wrong owner!\n";
  277. return NULL;
  278. }
  279. std::vector<CGHeroInstance *> pool;
  280. int sum=0, r;
  281. if(native)
  282. {
  283. for(std::map<ui32,CGHeroInstance *>::iterator i=heroesPool.begin(); i!=heroesPool.end(); i++)
  284. {
  285. if(pavailable[i->first] & 1<<player
  286. && i->second->type->heroType/2 == town->typeID
  287. && i->second->subID != notThatOne
  288. )
  289. {
  290. pool.push_back(i->second);
  291. }
  292. }
  293. if(!pool.size())
  294. return pickHeroFor(false,player,town,notThatOne);
  295. else
  296. return pool[rand()%pool.size()];
  297. }
  298. else
  299. {
  300. for(std::map<ui32,CGHeroInstance *>::iterator i=heroesPool.begin(); i!=heroesPool.end(); i++)
  301. {
  302. if(pavailable[i->first] & 1<<player
  303. && i->second->subID != notThatOne
  304. )
  305. {
  306. pool.push_back(i->second);
  307. sum += i->second->type->heroClass->selectionProbability[town->typeID];
  308. }
  309. }
  310. if(!pool.size())
  311. {
  312. tlog1 << "There are no heroes available for player " << player<<"!\n";
  313. return NULL;
  314. }
  315. r = rand()%sum;
  316. for(int i=0; i<pool.size(); i++)
  317. {
  318. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  319. if(r<0)
  320. return pool[i];
  321. }
  322. return pool[pool.size()-1];
  323. }
  324. }
  325. void CGameState::applyNL(IPack * pack)
  326. {
  327. switch(pack->getType())
  328. {
  329. case 101://NewTurn
  330. {
  331. NewTurn * n = static_cast<NewTurn*>(pack);
  332. day = n->day;
  333. BOOST_FOREACH(NewTurn::Hero h, n->heroes) //give mana/movement point
  334. {
  335. static_cast<CGHeroInstance*>(map->objects[h.id])->movement = h.move;
  336. static_cast<CGHeroInstance*>(map->objects[h.id])->mana = h.mana;
  337. }
  338. BOOST_FOREACH(SetResources h, n->res) //give resources
  339. applyNL(&h);
  340. BOOST_FOREACH(SetAvailableCreatures h, n->cres) //set available creatures in towns
  341. applyNL(&h);
  342. if(n->resetBuilded) //reset amount of structures set in this turn in towns
  343. BOOST_FOREACH(CGTownInstance* t, map->towns)
  344. t->builded = 0;
  345. break;
  346. }
  347. case 102: //set resource amount
  348. {
  349. SetResource *sr = static_cast<SetResource*>(pack);
  350. players[sr->player].resources[sr->resid] = sr->val;
  351. break;
  352. }
  353. case 104:
  354. {
  355. SetResources *sr = static_cast<SetResources*>(pack);
  356. for(int i=0;i<sr->res.size();i++)
  357. players[sr->player].resources[i] = sr->res[i];
  358. break;
  359. }
  360. case 105:
  361. {
  362. SetPrimSkill *sr = static_cast<SetPrimSkill*>(pack);
  363. CGHeroInstance *hero = getHero(sr->id);
  364. if(sr->which <4)
  365. {
  366. if(sr->abs)
  367. hero->primSkills[sr->which] = sr->val;
  368. else
  369. hero->primSkills[sr->which] += sr->val;
  370. }
  371. else if(sr->which == 4) //XP
  372. {
  373. if(sr->abs)
  374. hero->exp = sr->val;
  375. else
  376. hero->exp += sr->val;
  377. }
  378. break;
  379. }
  380. case 106:
  381. {
  382. SetSecSkill *sr = static_cast<SetSecSkill*>(pack);
  383. CGHeroInstance *hero = getHero(sr->id);
  384. if(hero->getSecSkillLevel(sr->which) == 0)
  385. {
  386. hero->secSkills.push_back(std::pair<int,int>(sr->which, sr->val));
  387. }
  388. else
  389. {
  390. for(unsigned i=0;i<hero->secSkills.size();i++)
  391. {
  392. if(hero->secSkills[i].first == sr->which)
  393. {
  394. if(sr->abs)
  395. hero->secSkills[i].second = sr->val;
  396. else
  397. hero->secSkills[i].second += sr->val;
  398. }
  399. }
  400. }
  401. break;
  402. }
  403. case 108:
  404. {
  405. HeroVisitCastle *vc = static_cast<HeroVisitCastle*>(pack);
  406. CGHeroInstance *h = getHero(vc->hid);
  407. CGTownInstance *t = getTown(vc->tid);
  408. if(vc->start())
  409. {
  410. if(vc->garrison())
  411. {
  412. t->garrisonHero = h;
  413. h->visitedTown = t;
  414. h->inTownGarrison = true;
  415. }
  416. else
  417. {
  418. t->visitingHero = h;
  419. h->visitedTown = t;
  420. h->inTownGarrison = false;
  421. }
  422. }
  423. else
  424. {
  425. if(vc->garrison())
  426. {
  427. t->garrisonHero = NULL;
  428. h->visitedTown = NULL;
  429. h->inTownGarrison = false;
  430. }
  431. else
  432. {
  433. t->visitingHero = NULL;
  434. h->visitedTown = NULL;
  435. h->inTownGarrison = false;
  436. }
  437. }
  438. break;
  439. }
  440. case 109:
  441. {
  442. ChangeSpells *rh = static_cast<ChangeSpells*>(pack);
  443. CGHeroInstance *hero = getHero(rh->hid);
  444. if(rh->learn)
  445. BOOST_FOREACH(ui32 sid, rh->spells)
  446. hero->spells.insert(sid);
  447. else
  448. BOOST_FOREACH(ui32 sid, rh->spells)
  449. hero->spells.erase(sid);
  450. break;
  451. }
  452. case 110:
  453. {
  454. SetMana *rh = static_cast<SetMana*>(pack);
  455. CGHeroInstance *hero = getHero(rh->hid);
  456. hero->mana = rh->val;
  457. break;
  458. }
  459. case 111:
  460. {
  461. SetMovePoints *rh = static_cast<SetMovePoints*>(pack);
  462. CGHeroInstance *hero = getHero(rh->hid);
  463. hero->movement = rh->val;
  464. break;
  465. }
  466. case 112:
  467. {
  468. FoWChange *rh = static_cast<FoWChange*>(pack);
  469. BOOST_FOREACH(int3 t, rh->tiles)
  470. players[rh->player].fogOfWarMap[t.x][t.y][t.z] = rh->mode;
  471. break;
  472. }
  473. case 113:
  474. {
  475. SetAvailableHeroes *rh = static_cast<SetAvailableHeroes*>(pack);
  476. players[rh->player].availableHeroes.clear();
  477. players[rh->player].availableHeroes.push_back(hpool.heroesPool[rh->hid1]);
  478. players[rh->player].availableHeroes.push_back(hpool.heroesPool[rh->hid2]);
  479. if(rh->flags & 1)
  480. {
  481. hpool.heroesPool[rh->hid1]->army.slots.clear();
  482. hpool.heroesPool[rh->hid1]->army.slots[0] = std::pair<ui32,si32>(VLC->creh->nameToID[hpool.heroesPool[rh->hid1]->type->refTypeStack[0]],1);
  483. }
  484. if(rh->flags & 2)
  485. {
  486. hpool.heroesPool[rh->hid2]->army.slots.clear();
  487. hpool.heroesPool[rh->hid2]->army.slots[0] = std::pair<ui32,si32>(VLC->creh->nameToID[hpool.heroesPool[rh->hid2]->type->refTypeStack[0]],1);
  488. }
  489. break;
  490. }
  491. case 500:
  492. {
  493. RemoveObject *rh = static_cast<RemoveObject*>(pack);
  494. CGObjectInstance *obj = map->objects[rh->id];
  495. if(obj->ID==34)
  496. {
  497. CGHeroInstance *h = static_cast<CGHeroInstance*>(obj);
  498. std::vector<CGHeroInstance*>::iterator nitr = std::find(map->heroes.begin(), map->heroes.end(),h);
  499. map->heroes.erase(nitr);
  500. int player = h->tempOwner;
  501. nitr = std::find(players[player].heroes.begin(), players[player].heroes.end(), h);
  502. players[player].heroes.erase(nitr);
  503. if(h->visitedTown)
  504. {
  505. if(h->inTownGarrison)
  506. h->visitedTown->garrisonHero = NULL;
  507. else
  508. h->visitedTown->visitingHero = NULL;
  509. h->visitedTown = NULL;
  510. }
  511. }
  512. map->objects[rh->id] = NULL;
  513. //unblock tiles
  514. if(obj->defInfo)
  515. {
  516. map->removeBlockVisTiles(obj);
  517. }
  518. break;
  519. }
  520. case 501://hero try-move
  521. {
  522. TryMoveHero * n = static_cast<TryMoveHero*>(pack);
  523. CGHeroInstance *h = static_cast<CGHeroInstance*>(map->objects[n->id]);
  524. h->movement = n->movePoints;
  525. if(n->start!=n->end && n->result)
  526. {
  527. map->removeBlockVisTiles(h);
  528. h->pos = n->end;
  529. map->addBlockVisTiles(h);
  530. }
  531. BOOST_FOREACH(int3 t, n->fowRevealed)
  532. players[h->getOwner()].fogOfWarMap[t.x][t.y][t.z] = 1;
  533. break;
  534. }
  535. case 502:
  536. {
  537. SetGarrisons * n = static_cast<SetGarrisons*>(pack);
  538. for(std::map<ui32,CCreatureSet>::iterator i = n->garrs.begin(); i!=n->garrs.end(); i++)
  539. {
  540. CArmedInstance *ai = static_cast<CArmedInstance*>(map->objects[i->first]);
  541. ai->army = i->second;
  542. if(ai->ID==98 && (static_cast<CGTownInstance*>(ai))->garrisonHero) //if there is a hero in garrison then we must update also his army
  543. const_cast<CGHeroInstance*>((static_cast<CGTownInstance*>(ai))->garrisonHero)->army = i->second;
  544. else if(ai->ID==34)
  545. {
  546. CGHeroInstance *h = static_cast<CGHeroInstance*>(ai);
  547. if(h->visitedTown && h->inTownGarrison)
  548. h->visitedTown->army = i->second;
  549. }
  550. }
  551. break;
  552. }
  553. case 503:
  554. {
  555. //SetStrInfo *ssi = static_cast<SetStrInfo*>(pack);
  556. //static_cast<CGTownInstance*>(map->objects[ssi->tid])->strInfo.creatures = ssi->cres;
  557. break;
  558. }
  559. case 504:
  560. {
  561. NewStructures *ns = static_cast<NewStructures*>(pack);
  562. CGTownInstance*t = static_cast<CGTownInstance*>(map->objects[ns->tid]);
  563. BOOST_FOREACH(si32 bid,ns->bid)
  564. t->builtBuildings.insert(bid);
  565. t->builded = ns->builded;
  566. break;
  567. }
  568. case 506:
  569. {
  570. SetAvailableCreatures *sac = static_cast<SetAvailableCreatures*>(pack);
  571. static_cast<CGTownInstance*>(map->objects[sac->tid])->strInfo.creatures = sac->creatures;
  572. break;
  573. }
  574. case 508:
  575. {
  576. SetHeroesInTown *sac = static_cast<SetHeroesInTown*>(pack);
  577. CGTownInstance *t = getTown(sac->tid);
  578. CGHeroInstance *v = getHero(sac->visiting), *g = getHero(sac->garrison);
  579. t->visitingHero = v;
  580. t->garrisonHero = g;
  581. if(v)
  582. {
  583. v->visitedTown = t;
  584. v->inTownGarrison = false;
  585. map->addBlockVisTiles(v);
  586. }
  587. if(g)
  588. {
  589. g->visitedTown = t;
  590. g->inTownGarrison = true;
  591. map->removeBlockVisTiles(g);
  592. }
  593. break;
  594. }
  595. case 509:
  596. {
  597. SetHeroArtifacts *sha = static_cast<SetHeroArtifacts*>(pack);
  598. CGHeroInstance *h = getHero(sha->hid);
  599. h->artifacts = sha->artifacts;
  600. h->artifWorn = sha->artifWorn;
  601. break;
  602. }
  603. case 515:
  604. {
  605. HeroRecruited *sha = static_cast<HeroRecruited*>(pack);
  606. CGHeroInstance *h = hpool.heroesPool[sha->hid];
  607. CGTownInstance *t = getTown(sha->tid);
  608. h->setOwner(sha->player);
  609. h->pos = sha->tile;
  610. h->movement = h->maxMovePoints(true);
  611. hpool.heroesPool.erase(sha->hid);
  612. if(h->id < 0)
  613. {
  614. h->id = map->objects.size();
  615. map->objects.push_back(h);
  616. }
  617. else
  618. map->objects[h->id] = h;
  619. map->heroes.push_back(h);
  620. players[h->tempOwner].heroes.push_back(h);
  621. map->addBlockVisTiles(h);
  622. t->visitingHero = h;
  623. h->visitedTown = t;
  624. h->inTownGarrison = false;
  625. break;
  626. }
  627. case 1001://set object property
  628. {
  629. SetObjectProperty *p = static_cast<SetObjectProperty*>(pack);
  630. if(p->what == 3) //set creatures amount
  631. {
  632. tlog5 << "Setting creatures amount in " << p->id << std::endl;
  633. static_cast<CGCreature*>(map->objects[p->id])->army.slots[0].second = p->val;
  634. break;
  635. }
  636. ui8 CGObjectInstance::*point;
  637. switch(p->what)
  638. {
  639. case 1:
  640. point = &CGObjectInstance::tempOwner;
  641. break;
  642. case 2:
  643. point = &CGObjectInstance::blockVisit;
  644. break;
  645. }
  646. map->objects[p->id]->*point = p->val;
  647. break;
  648. }
  649. case 2000:
  650. {
  651. HeroLevelUp * bs = static_cast<HeroLevelUp*>(pack);
  652. getHero(bs->heroid)->level = bs->level;
  653. break;
  654. }
  655. case 3000:
  656. {
  657. BattleStart * bs = static_cast<BattleStart*>(pack);
  658. curB = bs->info;
  659. break;
  660. }
  661. case 3001:
  662. {
  663. BattleNextRound *ns = static_cast<BattleNextRound*>(pack);
  664. curB->round = ns->round;
  665. for(int i=0; i<curB->stacks.size();i++)
  666. {
  667. curB->stacks[i]->state -= DEFENDING;
  668. curB->stacks[i]->state -= WAITING;
  669. curB->stacks[i]->state -= MOVED;
  670. curB->stacks[i]->state -= HAD_MORALE;
  671. curB->stacks[i]->counterAttacks = 1;
  672. }
  673. break;
  674. }
  675. case 3002:
  676. {
  677. BattleSetActiveStack *ns = static_cast<BattleSetActiveStack*>(pack);
  678. curB->activeStack = ns->stack;
  679. break;
  680. }
  681. case 3003:
  682. {
  683. BattleResult *br = static_cast<BattleResult*>(pack);
  684. //TODO: give exp, artifacts to winner, decrease armies (casualties)
  685. for(unsigned i=0;i<curB->stacks.size();i++)
  686. delete curB->stacks[i];
  687. delete curB;
  688. curB = NULL;
  689. break;
  690. }
  691. case 3004:
  692. {
  693. BattleStackMoved *br = static_cast<BattleStackMoved*>(pack);
  694. curB->getStack(br->stack)->position = br->tile;
  695. break;
  696. }
  697. case 3005:
  698. {
  699. BattleStackAttacked *br = static_cast<BattleStackAttacked*>(pack);
  700. CStack * at = curB->getStack(br->stackAttacked);
  701. at->amount = br->newAmount;
  702. at->firstHPleft = br->newHP;
  703. if(br->killed())
  704. at->state -= ALIVE;
  705. break;
  706. }
  707. case 3006:
  708. {
  709. BattleAttack *br = static_cast<BattleAttack*>(pack);
  710. CStack *attacker = curB->getStack(br->stackAttacking);
  711. if(br->counter())
  712. attacker->counterAttacks--;
  713. if(br->shot())
  714. attacker->shots--;
  715. applyNL(&br->bsa);
  716. break;
  717. }
  718. case 3007:
  719. {
  720. StartAction *br = static_cast<StartAction*>(pack);
  721. CStack *st = curB->getStack(br->ba.stackNumber);
  722. switch(br->ba.actionType)
  723. {
  724. case 3:
  725. st->state.insert(DEFENDING);
  726. break;
  727. case 8:
  728. st->state.insert(WAITING);
  729. break;
  730. case 2: case 6: case 7: case 9: case 10:
  731. st->state.insert(MOVED);
  732. break;
  733. }
  734. break;
  735. }
  736. case 3009:
  737. {
  738. SpellCasted *sc = static_cast<SpellCasted*>(pack);
  739. CGHeroInstance *h = (sc->side) ? getHero(curB->hero2) : getHero(curB->hero1);
  740. if(h)
  741. h->mana -= VLC->spellh->spells[sc->id].costs[sc->skill];
  742. //TODO: counter
  743. break;
  744. }
  745. case 3010:
  746. {
  747. SetStackEffect *sc = static_cast<SetStackEffect*>(pack);
  748. CStack *stack = curB->getStack(sc->stack);
  749. stack->effects.push_back(sc->effect);
  750. break;
  751. }
  752. }
  753. }
  754. void CGameState::apply(IPack * pack)
  755. {
  756. while(!mx->try_lock())
  757. boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  758. applyNL(pack);
  759. mx->unlock();
  760. }
  761. int CGameState::pickHero(int owner)
  762. {
  763. int h=-1;
  764. if(!map->getHero(h = scenarioOps->getIthPlayersSettings(owner).hero,0) && h>=0) //we haven't used selected hero
  765. return h;
  766. int f = scenarioOps->getIthPlayersSettings(owner).castle;
  767. int i=0;
  768. do //try to find free hero of our faction
  769. {
  770. i++;
  771. h = scenarioOps->getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  772. } while( map->getHero(h) && i<175);
  773. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  774. {
  775. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  776. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  777. if(!map->getHero(j))
  778. h=j;
  779. }
  780. return h;
  781. }
  782. CGHeroInstance *CGameState::getHero(int objid)
  783. {
  784. if(objid<0 || objid>=map->objects.size())
  785. return NULL;
  786. return static_cast<CGHeroInstance *>(map->objects[objid]);
  787. }
  788. CGTownInstance *CGameState::getTown(int objid)
  789. {
  790. if(objid<0 || objid>=map->objects.size())
  791. return NULL;
  792. return static_cast<CGTownInstance *>(map->objects[objid]);
  793. }
  794. std::pair<int,int> CGameState::pickObject(CGObjectInstance *obj)
  795. {
  796. switch(obj->ID)
  797. {
  798. case 65: //random artifact
  799. return std::pair<int,int>(5,(ran()%136)+7); //tylko sensowny zakres - na poczatku sa katapulty itp, na koncu specjalne i blanki
  800. case 66: //random treasure artifact
  801. return std::pair<int,int>(5,VLC->arth->treasures[ran()%VLC->arth->treasures.size()]->id);
  802. case 67: //random minor artifact
  803. return std::pair<int,int>(5,VLC->arth->minors[ran()%VLC->arth->minors.size()]->id);
  804. case 68: //random major artifact
  805. return std::pair<int,int>(5,VLC->arth->majors[ran()%VLC->arth->majors.size()]->id);
  806. case 69: //random relic artifact
  807. return std::pair<int,int>(5,VLC->arth->relics[ran()%VLC->arth->relics.size()]->id);
  808. case 70: //random hero
  809. {
  810. return std::pair<int,int>(34,pickHero(obj->tempOwner));
  811. }
  812. case 71: //random monster
  813. {
  814. int r;
  815. do
  816. {
  817. r = ran()%197;
  818. } while (vstd::contains(VLC->creh->notUsedMonsters,r));
  819. return std::pair<int,int>(54,r);
  820. }
  821. case 72: //random monster lvl1
  822. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  823. case 73: //random monster lvl2
  824. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  825. case 74: //random monster lvl3
  826. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  827. case 75: //random monster lvl4
  828. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  829. case 76: //random resource
  830. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  831. case 77: //random town
  832. {
  833. int align = ((CGTownInstance*)obj)->alignment,
  834. f;
  835. if(align>PLAYER_LIMIT-1)//same as owner / random
  836. {
  837. if(obj->tempOwner > PLAYER_LIMIT-1)
  838. f = -1; //random
  839. else
  840. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  841. }
  842. else
  843. {
  844. f = scenarioOps->getIthPlayersSettings(align).castle;
  845. }
  846. if(f<0) f = ran()%VLC->townh->towns.size();
  847. return std::pair<int,int>(98,f);
  848. }
  849. case 162: //random monster lvl5
  850. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  851. case 163: //random monster lvl6
  852. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  853. case 164: //random monster lvl7
  854. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  855. case 216: //random dwelling
  856. {
  857. int faction = ran()%F_NUMBER;
  858. CCreGen2ObjInfo* info =(CCreGen2ObjInfo*)obj->info;
  859. if (info->asCastle)
  860. {
  861. for(int i=0;i<map->objects.size();i++)
  862. {
  863. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  864. {
  865. randomizeObject(map->objects[i]); //we have to randomize the castle first
  866. faction = map->objects[i]->subID;
  867. break;
  868. }
  869. else if(map->objects[i]->ID==98 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  870. {
  871. faction = map->objects[i]->subID;
  872. break;
  873. }
  874. }
  875. }
  876. else
  877. {
  878. while((!(info->castles[0]&(1<<faction))))
  879. {
  880. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  881. break;
  882. faction = ran()%F_NUMBER;
  883. }
  884. }
  885. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  886. int cid = VLC->townh->towns[faction].basicCreatures[level];
  887. for(int i=0;i<VLC->objh->cregens.size();i++)
  888. if(VLC->objh->cregens[i]==cid)
  889. return std::pair<int,int>(17,i);
  890. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  891. return std::pair<int,int>(17,0);
  892. }
  893. case 217:
  894. {
  895. int faction = ran()%F_NUMBER;
  896. CCreGenObjInfo* info =(CCreGenObjInfo*)obj->info;
  897. if (info->asCastle)
  898. {
  899. for(int i=0;i<map->objects.size();i++)
  900. {
  901. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  902. {
  903. randomizeObject(map->objects[i]); //we have to randomize the castle first
  904. faction = map->objects[i]->subID;
  905. break;
  906. }
  907. else if(map->objects[i]->ID==98 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  908. {
  909. faction = map->objects[i]->subID;
  910. break;
  911. }
  912. }
  913. }
  914. else
  915. {
  916. while((!(info->castles[0]&(1<<faction))))
  917. {
  918. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  919. break;
  920. faction = ran()%F_NUMBER;
  921. }
  922. }
  923. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  924. for(int i=0;i<VLC->objh->cregens.size();i++)
  925. if(VLC->objh->cregens[i]==cid)
  926. return std::pair<int,int>(17,i);
  927. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  928. return std::pair<int,int>(17,0);
  929. }
  930. case 218:
  931. {
  932. CCreGen3ObjInfo* info =(CCreGen3ObjInfo*)obj->info;
  933. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  934. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  935. for(int i=0;i<VLC->objh->cregens.size();i++)
  936. if(VLC->objh->cregens[i]==cid)
  937. return std::pair<int,int>(17,i);
  938. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  939. return std::pair<int,int>(17,0);
  940. }
  941. }
  942. return std::pair<int,int>(-1,-1);
  943. }
  944. void CGameState::randomizeObject(CGObjectInstance *cur)
  945. {
  946. std::pair<int,int> ran = pickObject(cur);
  947. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  948. {
  949. if(cur->ID==98) //town - set def
  950. {
  951. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  952. if(t->hasCapitol())
  953. t->defInfo = capitols[t->subID];
  954. else if(t->hasFort())
  955. t->defInfo = forts[t->subID];
  956. else
  957. t->defInfo = villages[t->subID];
  958. }
  959. return;
  960. }
  961. else if(ran.first==34)//special code for hero
  962. {
  963. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  964. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  965. cur->ID = ran.first;
  966. h->portrait = cur->subID = ran.second;
  967. h->type = VLC->heroh->heroes[ran.second];
  968. map->heroes.push_back(h);
  969. return; //TODO: maybe we should do something with definfo?
  970. }
  971. else if(ran.first==98)//special code for town
  972. {
  973. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  974. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  975. cur->ID = ran.first;
  976. cur->subID = ran.second;
  977. t->town = &VLC->townh->towns[ran.second];
  978. if(t->hasCapitol())
  979. t->defInfo = capitols[t->subID];
  980. else if(t->hasFort())
  981. t->defInfo = forts[t->subID];
  982. else
  983. t->defInfo = villages[t->subID];
  984. map->towns.push_back(t);
  985. return;
  986. }
  987. //we have to replace normal random object
  988. cur->ID = ran.first;
  989. cur->subID = ran.second;
  990. map->defs.insert(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  991. if(!cur->defInfo)
  992. {
  993. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  994. return;
  995. }
  996. }
  997. int CGameState::getDate(int mode) const
  998. {
  999. int temp;
  1000. switch (mode)
  1001. {
  1002. case 0:
  1003. return day;
  1004. break;
  1005. case 1:
  1006. temp = (day)%7;
  1007. if (temp)
  1008. return temp;
  1009. else return 7;
  1010. break;
  1011. case 2:
  1012. temp = ((day-1)/7)+1;
  1013. if (!(temp%4))
  1014. return 4;
  1015. else
  1016. return (temp%4);
  1017. break;
  1018. case 3:
  1019. return ((day-1)/28)+1;
  1020. break;
  1021. }
  1022. return 0;
  1023. }
  1024. CGameState::CGameState()
  1025. {
  1026. mx = new boost::shared_mutex();
  1027. }
  1028. CGameState::~CGameState()
  1029. {
  1030. delete mx;
  1031. }
  1032. void CGameState::init(StartInfo * si, Mapa * map, int Seed)
  1033. {
  1034. day = 0;
  1035. seed = Seed;
  1036. ran.seed((boost::int32_t)seed);
  1037. scenarioOps = si;
  1038. this->map = map;
  1039. loadTownDInfos();
  1040. //picking random factions for players
  1041. for(int i=0;i<scenarioOps->playerInfos.size();i++)
  1042. {
  1043. if(scenarioOps->playerInfos[i].castle==-1)
  1044. {
  1045. int f;
  1046. do
  1047. {
  1048. f = ran()%F_NUMBER;
  1049. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  1050. scenarioOps->playerInfos[i].castle = f;
  1051. }
  1052. }
  1053. //randomizing objects
  1054. for(int no=0; no<map->objects.size(); ++no)
  1055. {
  1056. randomizeObject(map->objects[no]);
  1057. if(map->objects[no]->ID==26)
  1058. {
  1059. map->objects[no]->defInfo->handler=NULL;
  1060. map->removeBlockVisTiles(map->objects[no]);
  1061. map->objects[no]->defInfo->blockMap[5] = 255;
  1062. map->addBlockVisTiles(map->objects[no]);
  1063. }
  1064. map->objects[no]->hoverName = VLC->objh->names[map->objects[no]->ID];
  1065. }
  1066. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  1067. /*********give starting hero****************************************/
  1068. for(int i=0;i<PLAYER_LIMIT;i++)
  1069. {
  1070. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==RoE))
  1071. {
  1072. int3 hpos = map->players[i].posOfMainTown;
  1073. hpos.x+=1;// hpos.y+=1;
  1074. int j;
  1075. for(j=0; j<scenarioOps->playerInfos.size(); j++)
  1076. if(scenarioOps->playerInfos[j].color == i)
  1077. break;
  1078. if(j == scenarioOps->playerInfos.size())
  1079. continue;
  1080. int h=pickHero(i);
  1081. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(34,h,hpos,i));
  1082. nnn->id = map->objects.size();
  1083. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  1084. for(int o=0;o<map->towns.size();o++) //find main town
  1085. {
  1086. if(map->towns[o]->pos == hpos)
  1087. {
  1088. map->towns[o]->visitingHero = nnn;
  1089. nnn->visitedTown = map->towns[o];
  1090. nnn->inTownGarrison = false;
  1091. break;
  1092. }
  1093. }
  1094. nnn->initHero();
  1095. map->heroes.push_back(nnn);
  1096. map->objects.push_back(nnn);
  1097. map->addBlockVisTiles(nnn);
  1098. }
  1099. }
  1100. /*********creating players entries in gs****************************************/
  1101. for (int i=0; i<scenarioOps->playerInfos.size();i++)
  1102. {
  1103. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  1104. ins.second.color=ins.first;
  1105. ins.second.serial=i;
  1106. players.insert(ins);
  1107. }
  1108. /******************RESOURCES****************************************************/
  1109. //TODO: computer player should receive other amount of resource than computer (depending on difficulty)
  1110. std::vector<int> startres;
  1111. std::ifstream tis("config/startres.txt");
  1112. int k;
  1113. for (int j=0;j<scenarioOps->difficulty;j++)
  1114. {
  1115. tis >> k;
  1116. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1117. tis>>k;
  1118. }
  1119. tis >> k;
  1120. for (int i=0;i<RESOURCE_QUANTITY;i++)
  1121. {
  1122. tis >> k;
  1123. startres.push_back(k);
  1124. }
  1125. tis.close();
  1126. tis.clear();
  1127. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1128. {
  1129. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1130. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1131. (*i).second.resources[x] = startres[x];
  1132. }
  1133. tis.open("config/resources.txt");
  1134. tis >> k;
  1135. int pom;
  1136. for(int i=0;i<k;i++)
  1137. {
  1138. tis >> pom;
  1139. resVals.push_back(pom);
  1140. }
  1141. /*************************HEROES************************************************/
  1142. std::set<int> hids;
  1143. for(int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1144. if(map->allowedHeroes[i])
  1145. hids.insert(i);
  1146. for (int i=0; i<map->heroes.size();i++) //heroes instances
  1147. {
  1148. if (map->heroes[i]->getOwner()<0)
  1149. {
  1150. tlog2 << "Warning - hero with uninitialized owner!\n";
  1151. continue;
  1152. }
  1153. CGHeroInstance * vhi = (map->heroes[i]);
  1154. vhi->initHero();
  1155. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1156. hids.erase(vhi->subID);
  1157. }
  1158. for(int i=0; i<map->predefinedHeroes.size(); i++)
  1159. {
  1160. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1161. continue;
  1162. map->predefinedHeroes[i]->initHero();
  1163. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1164. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1165. hids.erase(map->predefinedHeroes[i]->subID);
  1166. }
  1167. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go into the pool
  1168. {
  1169. CGHeroInstance * vhi = new CGHeroInstance();
  1170. vhi->initHero(hid);
  1171. hpool.heroesPool[hid] = vhi;
  1172. hpool.pavailable[hid] = 0xff;
  1173. }
  1174. for(int i=0; i<map->disposedHeroes.size(); i++)
  1175. {
  1176. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1177. }
  1178. /*************************FOG**OF**WAR******************************************/
  1179. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1180. {
  1181. k->second.fogOfWarMap.resize(map->width);
  1182. for(int g=0; g<map->width; ++g)
  1183. k->second.fogOfWarMap[g].resize(map->height);
  1184. for(int g=-0; g<map->width; ++g)
  1185. for(int h=0; h<map->height; ++h)
  1186. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1187. for(int g=0; g<map->width; ++g)
  1188. for(int h=0; h<map->height; ++h)
  1189. for(int v=0; v<map->twoLevel+1; ++v)
  1190. k->second.fogOfWarMap[g][h][v] = 0;
  1191. for(int xd=0; xd<map->width; ++xd) //revealing part of map around heroes
  1192. {
  1193. for(int yd=0; yd<map->height; ++yd)
  1194. {
  1195. for(int ch=0; ch<k->second.heroes.size(); ++ch)
  1196. {
  1197. int deltaX = (k->second.heroes[ch]->getPosition(false).x-xd)*(k->second.heroes[ch]->getPosition(false).x-xd);
  1198. int deltaY = (k->second.heroes[ch]->getPosition(false).y-yd)*(k->second.heroes[ch]->getPosition(false).y-yd);
  1199. if(deltaX+deltaY<k->second.heroes[ch]->getSightDistance()*k->second.heroes[ch]->getSightDistance())
  1200. k->second.fogOfWarMap[xd][yd][k->second.heroes[ch]->getPosition(false).z] = 1;
  1201. }
  1202. }
  1203. }
  1204. //starting bonus
  1205. if(si->playerInfos[k->second.serial].bonus==brandom)
  1206. si->playerInfos[k->second.serial].bonus = ran()%3;
  1207. switch(si->playerInfos[k->second.serial].bonus)
  1208. {
  1209. case bgold:
  1210. k->second.resources[6] += 500 + (ran()%6)*100;
  1211. break;
  1212. case bresource:
  1213. {
  1214. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1215. if(res == 127)
  1216. {
  1217. k->second.resources[0] += 5 + ran()%6;
  1218. k->second.resources[2] += 5 + ran()%6;
  1219. }
  1220. else
  1221. {
  1222. k->second.resources[res] += 3 + ran()%4;
  1223. }
  1224. break;
  1225. }
  1226. case bartifact:
  1227. {
  1228. if(!k->second.heroes.size())
  1229. {
  1230. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1231. break;
  1232. }
  1233. CArtifact *toGive;
  1234. do
  1235. {
  1236. toGive = VLC->arth->treasures[ran() % VLC->arth->treasures.size()];
  1237. } while (!map->allowedArtifact[toGive->id]);
  1238. CGHeroInstance *hero = k->second.heroes[0];
  1239. std::vector<ui16>::iterator slot = vstd::findFirstNot(hero->artifWorn,toGive->possibleSlots);
  1240. if(slot!=toGive->possibleSlots.end())
  1241. hero->artifWorn[*slot] = toGive->id;
  1242. else
  1243. hero->artifacts.push_back(toGive->id);
  1244. }
  1245. }
  1246. }
  1247. /****************************TOWNS************************************************/
  1248. for (int i=0;i<map->towns.size();i++)
  1249. {
  1250. CGTownInstance * vti =(map->towns[i]);
  1251. if(!vti->town)
  1252. vti->town = &VLC->townh->towns[vti->subID];
  1253. if (vti->name.length()==0) // if town hasn't name we draw it
  1254. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1255. //init buildings
  1256. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1257. {
  1258. vti->builtBuildings.erase(-50);
  1259. vti->builtBuildings.insert(10);
  1260. vti->builtBuildings.insert(5);
  1261. vti->builtBuildings.insert(30);
  1262. if(ran()%2)
  1263. vti->builtBuildings.insert(31);
  1264. }
  1265. //init spells
  1266. vti->spells.resize(SPELL_LEVELS);
  1267. CSpell *s;
  1268. for(int z=0; z<vti->obligatorySpells.size();z++)
  1269. {
  1270. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1271. vti->spells[s->level-1].push_back(s->id);
  1272. vti->possibleSpells -= s->id;
  1273. }
  1274. while(vti->possibleSpells.size())
  1275. {
  1276. ui32 total=0, sel=-1;
  1277. for(int ps=0;ps<vti->possibleSpells.size();ps++)
  1278. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1279. int r = (total)? ran()%total : -1;
  1280. for(int ps=0; ps<vti->possibleSpells.size();ps++)
  1281. {
  1282. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1283. if(r<0)
  1284. {
  1285. sel = ps;
  1286. break;
  1287. }
  1288. }
  1289. if(sel<0)
  1290. sel=0;
  1291. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1292. vti->spells[s->level-1].push_back(s->id);
  1293. vti->possibleSpells -= s->id;
  1294. }
  1295. //init garrisons
  1296. for (std::map<si32,std::pair<ui32,si32> >::iterator j=vti->army.slots.begin(); j!=vti->army.slots.end();j++)
  1297. {
  1298. if(j->second.first > 196 && j->second.first < 211)
  1299. {
  1300. if(j->second.first%2)
  1301. j->second.first = vti->town->basicCreatures[ (j->second.first-197) / 2 ];
  1302. else
  1303. j->second.first = vti->town->upgradedCreatures[ (j->second.first-197) / 2 ];
  1304. }
  1305. }
  1306. players[vti->getOwner()].towns.push_back(vti);
  1307. }
  1308. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1309. {
  1310. if(k->first==-1 || k->first==255)
  1311. continue;
  1312. for(int xd=0; xd<map->width; ++xd) //revealing part of map around towns
  1313. {
  1314. for(int yd=0; yd<map->height; ++yd)
  1315. {
  1316. for(int ch=0; ch<k->second.towns.size(); ++ch)
  1317. {
  1318. int deltaX = (k->second.towns[ch]->pos.x-xd)*(k->second.towns[ch]->pos.x-xd);
  1319. int deltaY = (k->second.towns[ch]->pos.y-yd)*(k->second.towns[ch]->pos.y-yd);
  1320. if(deltaX+deltaY<k->second.towns[ch]->getSightDistance()*k->second.towns[ch]->getSightDistance())
  1321. k->second.fogOfWarMap[xd][yd][k->second.towns[ch]->pos.z] = 1;
  1322. }
  1323. }
  1324. }
  1325. //init visiting and garrisoned heroes
  1326. for(int l=0; l<k->second.heroes.size();l++)
  1327. {
  1328. for(int m=0; m<k->second.towns.size();m++)
  1329. {
  1330. int3 vistile = k->second.towns[m]->pos; vistile.x--; //tile next to the entrance
  1331. if(vistile == k->second.heroes[l]->pos || k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1332. {
  1333. k->second.towns[m]->visitingHero = k->second.heroes[l];
  1334. k->second.heroes[l]->visitedTown = k->second.towns[m];
  1335. k->second.heroes[l]->inTownGarrison = false;
  1336. if(k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1337. k->second.heroes[l]->pos.x -= 1;
  1338. break;
  1339. }
  1340. }
  1341. }
  1342. }
  1343. }
  1344. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1345. {
  1346. return true;
  1347. }
  1348. int CGameState::battleGetStack(int pos)
  1349. {
  1350. if(!curB)
  1351. return -1;
  1352. for(int g=0; g<curB->stacks.size(); ++g)
  1353. {
  1354. if((curB->stacks[g]->position == pos
  1355. || (curB->stacks[g]->creature->isDoubleWide()
  1356. &&( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos)
  1357. || (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos) )
  1358. ))
  1359. && curB->stacks[g]->alive()
  1360. )
  1361. return curB->stacks[g]->ID;
  1362. }
  1363. return -1;
  1364. }
  1365. UpgradeInfo CGameState::getUpgradeInfo(CArmedInstance *obj, int stackPos)
  1366. {
  1367. UpgradeInfo ret;
  1368. CCreature *base = &VLC->creh->creatures[obj->army.slots[stackPos].first];
  1369. if((obj->ID == 98) || ((obj->ID == 34) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
  1370. {
  1371. CGTownInstance * t;
  1372. if(obj->ID == 98)
  1373. t = static_cast<CGTownInstance *>(const_cast<CArmedInstance *>(obj));
  1374. else
  1375. t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
  1376. for(std::set<si32>::iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++)
  1377. {
  1378. if( (*i) >= 37 && (*i) < 44 ) //upgraded creature dwelling
  1379. {
  1380. int nid = t->town->upgradedCreatures[(*i)-37]; //upgrade offered by that building
  1381. if(base->upgrades.find(nid) != base->upgrades.end()) //possible upgrade
  1382. {
  1383. ret.newID.push_back(nid);
  1384. ret.cost.push_back(std::set<std::pair<int,int> >());
  1385. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1386. {
  1387. int dif = VLC->creh->creatures[nid].cost[j] - base->cost[j];
  1388. if(dif)
  1389. ret.cost[ret.cost.size()-1].insert(std::make_pair(j,dif));
  1390. }
  1391. }
  1392. }
  1393. }//end for
  1394. }
  1395. //TODO: check if hero ability makes some upgrades possible
  1396. if(ret.newID.size())
  1397. ret.oldID = base->idNumber;
  1398. return ret;
  1399. }
  1400. float CGameState::getMarketEfficiency( int player, int mode/*=0*/ )
  1401. {
  1402. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1403. if(mode) return -1; //todo - support other modes
  1404. int mcount = 0;
  1405. for(int i=0;i<players[player].towns.size();i++)
  1406. if(vstd::contains(players[player].towns[i]->builtBuildings,14))
  1407. mcount++;
  1408. float ret = std::min(((float)mcount+1.0f)/20.0f,0.5f);
  1409. return ret;
  1410. }
  1411. std::set<int3> CGameState::tilesToReveal(int3 pos, int radious, int player) const
  1412. {
  1413. std::set<int3> ret;
  1414. int xbeg = pos.x - radious - 2;
  1415. if(xbeg < 0)
  1416. xbeg = 0;
  1417. int xend = pos.x + radious + 2;
  1418. if(xend >= map->width)
  1419. xend = map->width;
  1420. int ybeg = pos.y - radious - 2;
  1421. if(ybeg < 0)
  1422. ybeg = 0;
  1423. int yend = pos.y + radious + 2;
  1424. if(yend >= map->height)
  1425. yend = map->height;
  1426. for(int xd=xbeg; xd<xend; ++xd) //revealing part of map around heroes
  1427. {
  1428. for(int yd=ybeg; yd<yend; ++yd)
  1429. {
  1430. int deltaX = (pos.x-xd)*(pos.x-xd);
  1431. int deltaY = (pos.y-yd)*(pos.y-yd);
  1432. if(deltaX+deltaY<radious*radious)
  1433. {
  1434. if(player<0 || players.find(player)->second.fogOfWarMap[xd][yd][pos.z]==0)
  1435. {
  1436. ret.insert(int3(xd,yd,pos.z));
  1437. }
  1438. }
  1439. }
  1440. }
  1441. return ret;
  1442. }
  1443. void CGameState::loadTownDInfos()
  1444. {
  1445. for(int i=0;i<F_NUMBER;i++)
  1446. {
  1447. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1448. forts[i] = VLC->dobjinfo->castles[i];
  1449. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1450. }
  1451. }
  1452. int BattleInfo::calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting)
  1453. {
  1454. int attackerAttackBonus = attacker->creature->attack + (attackerHero ? attackerHero->getPrimSkillLevel(0) : 0);
  1455. if(attacker->getEffect(56)) //frenzy for attacker
  1456. {
  1457. attackerAttackBonus += (VLC->spellh->spells[attacker->getEffect(56)->id].powers[attacker->getEffect(56)->level]/100.0) *(attacker->creature->defence + (attackerHero ? attackerHero->getPrimSkillLevel(1) : 0));
  1458. }
  1459. int defenderDefenseBonus = defender->creature->defence + (defendingHero ? defendingHero->getPrimSkillLevel(1) : 0);
  1460. if(defender->getEffect(56)) //frenzy for defender
  1461. {
  1462. defenderDefenseBonus = 0;
  1463. }
  1464. int attackDefenseBonus = attackerAttackBonus - defenderDefenseBonus;
  1465. if(defender->getEffect(48)) //defender's prayer handling
  1466. {
  1467. attackDefenseBonus -= VLC->spellh->spells[defender->getEffect(48)->id].powers[defender->getEffect(48)->level];
  1468. }
  1469. if(attacker->getEffect(48)) //attacker's prayer handling
  1470. {
  1471. attackDefenseBonus += VLC->spellh->spells[attacker->getEffect(48)->id].powers[attacker->getEffect(48)->level];
  1472. }
  1473. if(defender->getEffect(46)) //stone skin handling
  1474. {
  1475. attackDefenseBonus -= VLC->spellh->spells[defender->getEffect(46)->id].powers[defender->getEffect(46)->level];
  1476. }
  1477. if(attacker->getEffect(45)) //weakness handling
  1478. {
  1479. attackDefenseBonus -= VLC->spellh->spells[attacker->getEffect(45)->id].powers[attacker->getEffect(45)->level];
  1480. }
  1481. if(!shooting && attacker->getEffect(43)) //bloodlust handling
  1482. {
  1483. attackDefenseBonus += VLC->spellh->spells[attacker->getEffect(43)->id].powers[attacker->getEffect(43)->level];
  1484. }
  1485. int damageBase = 0;
  1486. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  1487. {
  1488. damageBase = attacker->creature->damageMin;
  1489. damageBase -= VLC->spellh->spells[attacker->getEffect(42)->id].powers[attacker->getEffect(42)->level];
  1490. }
  1491. else if(attacker->getEffect(41)) //bless handling
  1492. {
  1493. damageBase = attacker->creature->damageMax;
  1494. damageBase += VLC->spellh->spells[attacker->getEffect(41)->id].powers[attacker->getEffect(41)->level];
  1495. }
  1496. else if(attacker->creature->damageMax == attacker->creature->damageMin) //constant damage
  1497. {
  1498. damageBase = attacker->creature->damageMin;
  1499. }
  1500. else
  1501. {
  1502. damageBase = rand()%(attacker->creature->damageMax - attacker->creature->damageMin) + attacker->creature->damageMin + 1;
  1503. }
  1504. float dmgBonusMultiplier = 1.0f;
  1505. if(attackDefenseBonus < 0) //decreasing dmg
  1506. {
  1507. if(0.02f * (-attackDefenseBonus) > 0.3f)
  1508. {
  1509. dmgBonusMultiplier += -0.3f;
  1510. }
  1511. else
  1512. {
  1513. dmgBonusMultiplier += 0.02f * attackDefenseBonus;
  1514. }
  1515. }
  1516. else //increasing dmg
  1517. {
  1518. if(0.05f * attackDefenseBonus > 4.0f)
  1519. {
  1520. dmgBonusMultiplier += 4.0f;
  1521. }
  1522. else
  1523. {
  1524. dmgBonusMultiplier += 0.05f * attackDefenseBonus;
  1525. }
  1526. }
  1527. //handling secondary abilities
  1528. if(attackerHero)
  1529. {
  1530. if(shooting)
  1531. {
  1532. switch(attackerHero->getSecSkillLevel(1)) //archery
  1533. {
  1534. case 1: //basic
  1535. dmgBonusMultiplier *= 1.1f;
  1536. break;
  1537. case 2: //advanced
  1538. dmgBonusMultiplier *= 1.25f;
  1539. break;
  1540. case 3: //expert
  1541. dmgBonusMultiplier *= 1.5f;
  1542. break;
  1543. }
  1544. }
  1545. else
  1546. {
  1547. switch(attackerHero->getSecSkillLevel(22)) //offence
  1548. {
  1549. case 1: //basic
  1550. dmgBonusMultiplier *= 1.1f;
  1551. break;
  1552. case 2: //advanced
  1553. dmgBonusMultiplier *= 1.2f;
  1554. break;
  1555. case 3: //expert
  1556. dmgBonusMultiplier *= 1.3f;
  1557. break;
  1558. }
  1559. }
  1560. }
  1561. if(defendingHero)
  1562. {
  1563. switch(defendingHero->getSecSkillLevel(23)) //armourer
  1564. {
  1565. case 1: //basic
  1566. dmgBonusMultiplier *= 0.95f;
  1567. break;
  1568. case 2: //advanced
  1569. dmgBonusMultiplier *= 0.9f;
  1570. break;
  1571. case 3: //expert
  1572. dmgBonusMultiplier *= 0.85f;
  1573. break;
  1574. }
  1575. }
  1576. //handling spell effects
  1577. if(!shooting && defender->getEffect(27)) //shield
  1578. {
  1579. if(defender->getEffect(27)->level<=1) //none or basic
  1580. dmgBonusMultiplier *= 0.85f;
  1581. else //adv or expert
  1582. dmgBonusMultiplier *= 0.7f;
  1583. }
  1584. if(shooting && defender->getEffect(28)) //air shield
  1585. {
  1586. if(defender->getEffect(28)->level<=1) //none or basic
  1587. dmgBonusMultiplier *= 0.75f;
  1588. else //adv or expert
  1589. dmgBonusMultiplier *= 0.5f;
  1590. }
  1591. if(attacker->getEffect(42)) //curse, second part of handling
  1592. {
  1593. if(attacker->getEffect(42)->level>=2) //adv or expert
  1594. dmgBonusMultiplier *= 0.8f;
  1595. }
  1596. return (float)damageBase * (float)attacker->amount * dmgBonusMultiplier;
  1597. }
  1598. void BattleInfo::calculateCasualties( std::set<std::pair<ui32,si32> > *casualties )
  1599. {
  1600. for(int i=0; i<stacks.size();i++)//setting casualties
  1601. {
  1602. if(!stacks[i]->alive())
  1603. {
  1604. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount));
  1605. }
  1606. else if(stacks[i]->amount != stacks[i]->baseAmount)
  1607. {
  1608. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount - stacks[i]->amount));
  1609. }
  1610. }
  1611. }
  1612. CStack * BattleInfo::getNextStack()
  1613. {
  1614. CStack *current = getStack(activeStack);
  1615. for (int i = 0; i < stacks.size(); i++) //find fastest not moved/waited stack (stacks vector is sorted by speed)
  1616. {
  1617. if(vstd::contains(stacks[i]->state,DEFENDING)
  1618. ||vstd::contains(stacks[i]->state,WAITING)
  1619. ||vstd::contains(stacks[i]->state,MOVED)
  1620. ||!stacks[i]->alive()
  1621. ||stacks[i] == current
  1622. )
  1623. continue;
  1624. return stacks[i];
  1625. }
  1626. for (int i = stacks.size() - 1; i >= 0 ; i--) //find slowest waiting stack
  1627. {
  1628. if(vstd::contains(stacks[i]->state,DEFENDING)
  1629. ||vstd::contains(stacks[i]->state,MOVED)
  1630. ||!stacks[i]->alive()
  1631. ||stacks[i] == current
  1632. )
  1633. continue;
  1634. return stacks[i];
  1635. }
  1636. return NULL; //all stacks moved or defending!
  1637. }
  1638. std::vector<CStack> BattleInfo::getStackQueue()
  1639. {
  1640. std::vector<CStack> ret;
  1641. std::vector<int> taken; //if non-zero value, corresponding stack has been placed in ret
  1642. taken.resize(stacks.size());
  1643. for(int g=0; g<taken.size(); ++g)
  1644. {
  1645. taken[g] = 0;
  1646. }
  1647. for(int moved=0; moved<2; ++moved) //in first cycle we add stacks that can act in current turn, in second one the rest of them
  1648. {
  1649. for(int gc=0; gc<stacks.size(); ++gc)
  1650. {
  1651. int id = -1, speed = -1;
  1652. for(int i=0; i<stacks.size(); ++i) //find not waited stacks only
  1653. {
  1654. if((moved == 1 ||!vstd::contains(stacks[i]->state,DEFENDING))
  1655. && stacks[i]->alive()
  1656. && (moved == 1 || !vstd::contains(stacks[i]->state,MOVED))
  1657. && !vstd::contains(stacks[i]->state,WAITING)
  1658. && taken[i]==0)
  1659. {
  1660. if(speed == -1 || stacks[i]->speed() > speed)
  1661. {
  1662. id = i;
  1663. speed = stacks[i]->speed();
  1664. }
  1665. }
  1666. }
  1667. if(id != -1)
  1668. {
  1669. ret.push_back(*stacks[id]);
  1670. taken[id] = 1;
  1671. }
  1672. else //choose something from not moved stacks
  1673. {
  1674. int id = -1, speed = 10000; //infinite speed
  1675. for(int i=0; i<stacks.size(); ++i) //find waited stacks only
  1676. {
  1677. if((moved == 1 ||!vstd::contains(stacks[i]->state,DEFENDING))
  1678. && stacks[i]->alive()
  1679. && (moved == 1 || !vstd::contains(stacks[i]->state,MOVED))
  1680. && vstd::contains(stacks[i]->state,WAITING)
  1681. && taken[i]==0)
  1682. {
  1683. if(stacks[i]->speed() < speed) //slowest one
  1684. {
  1685. id = i;
  1686. speed = stacks[i]->speed();
  1687. }
  1688. }
  1689. }
  1690. if(id != -1)
  1691. {
  1692. ret.push_back(*stacks[id]);
  1693. taken[id] = 1;
  1694. }
  1695. else
  1696. {
  1697. break; //no stacks have been found, so none of them will be found in next iterations
  1698. }
  1699. }
  1700. }
  1701. }
  1702. return ret;
  1703. }