CGameState.cpp 50 KB

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