CGameState.cpp 50 KB

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