CGameState.cpp 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312
  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 "VCMI_Lib.h"
  17. #include "Connection.h"
  18. #include "map.h"
  19. #include "../StartInfo.h"
  20. #include "NetPacks.h"
  21. #include <boost/foreach.hpp>
  22. #include <boost/lexical_cast.hpp>
  23. #include <boost/thread.hpp>
  24. #include <boost/thread/shared_mutex.hpp>
  25. #include "RegisterTypes.cpp"
  26. boost::rand48 ran;
  27. #ifdef min
  28. #undef min
  29. #endif
  30. #ifdef max
  31. #undef max
  32. #endif
  33. /*
  34. * CGameState.cpp, part of VCMI engine
  35. *
  36. * Authors: listed in file AUTHORS in main folder
  37. *
  38. * License: GNU General Public License v2.0 or later
  39. * Full text of license available in license.txt file, in main folder
  40. *
  41. */
  42. void foofoofoo()
  43. {
  44. //never called function to force instantation of templates
  45. int *ccc = NULL;
  46. registerTypes((CISer<CConnection>&)*ccc);
  47. registerTypes((COSer<CConnection>&)*ccc);
  48. registerTypes((CSaveFile&)*ccc);
  49. registerTypes((CLoadFile&)*ccc);
  50. registerTypes((CTypeList&)*ccc);
  51. }
  52. class CBaseForGSApply
  53. {
  54. public:
  55. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  56. };
  57. template <typename T> class CApplyOnGS : public CBaseForGSApply
  58. {
  59. public:
  60. void applyOnGS(CGameState *gs, void *pack) const
  61. {
  62. T *ptr = static_cast<T*>(pack);
  63. while(!gs->mx->try_lock())
  64. boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  65. ptr->applyGs(gs);
  66. gs->mx->unlock();
  67. }
  68. };
  69. class CGSApplier
  70. {
  71. public:
  72. std::map<ui16,CBaseForGSApply*> apps;
  73. CGSApplier()
  74. {
  75. registerTypes2(*this);
  76. }
  77. template<typename T> void registerType(const T * t=NULL)
  78. {
  79. ui16 ID = typeList.registerType(t);
  80. apps[ID] = new CApplyOnGS<T>;
  81. }
  82. } *applierGs = NULL;
  83. void MetaString::getLocalString(const std::pair<ui8,ui32> &txt, std::string &dst) const
  84. {
  85. int type = txt.first, ser = txt.second;
  86. if(type == ART_NAMES)
  87. {
  88. dst = VLC->arth->artifacts[ser].Name();
  89. }
  90. else if(type == CRE_PL_NAMES)
  91. {
  92. dst = VLC->creh->creatures[ser].namePl;
  93. }
  94. else if(type == MINE_NAMES)
  95. {
  96. dst = VLC->generaltexth->mines[ser].first;
  97. }
  98. else if(type == MINE_EVNTS)
  99. {
  100. dst = VLC->generaltexth->mines[ser].second;
  101. }
  102. else if(type == SPELL_NAME)
  103. {
  104. dst = VLC->spellh->spells[ser].name;
  105. }
  106. else if(type == CRE_SING_NAMES)
  107. {
  108. dst = VLC->creh->creatures[ser].nameSing;
  109. }
  110. else
  111. {
  112. std::vector<std::string> *vec;
  113. switch(type)
  114. {
  115. case GENERAL_TXT:
  116. vec = &VLC->generaltexth->allTexts;
  117. break;
  118. case XTRAINFO_TXT:
  119. vec = &VLC->generaltexth->xtrainfo;
  120. break;
  121. case OBJ_NAMES:
  122. vec = &VLC->generaltexth->names;
  123. break;
  124. case RES_NAMES:
  125. vec = &VLC->generaltexth->restypes;
  126. break;
  127. case ARRAY_TXT:
  128. vec = &VLC->generaltexth->arraytxt;
  129. break;
  130. case CREGENS:
  131. vec = &VLC->generaltexth->creGens;
  132. break;
  133. case CREGENS4:
  134. vec = &VLC->generaltexth->creGens4;
  135. break;
  136. case ADVOB_TXT:
  137. vec = &VLC->generaltexth->advobtxt;
  138. break;
  139. case ART_EVNTS:
  140. vec = &VLC->generaltexth->artifEvents;
  141. break;
  142. case SEC_SKILL_NAME:
  143. vec = &VLC->generaltexth->skillName;
  144. break;
  145. }
  146. dst = (*vec)[ser];
  147. }
  148. }
  149. DLL_EXPORT void MetaString::toString(std::string &dst) const
  150. {
  151. size_t exSt = 0, loSt = 0, nums = 0;
  152. dst.clear();
  153. for(size_t i=0;i<message.size();++i)
  154. {//TEXACT_STRING, TLOCAL_STRING, TNUMBER, TREPLACE_ESTRING, TREPLACE_LSTRING, TREPLACE_NUMBER
  155. switch(message[i])
  156. {
  157. case TEXACT_STRING:
  158. dst += exactStrings[exSt++];
  159. break;
  160. case TLOCAL_STRING:
  161. {
  162. std::string hlp;
  163. getLocalString(localStrings[loSt++], hlp);
  164. dst += hlp;
  165. }
  166. break;
  167. case TNUMBER:
  168. dst += boost::lexical_cast<std::string>(numbers[nums++]);
  169. break;
  170. case TREPLACE_ESTRING:
  171. dst.replace(dst.find("%s"), 2, exactStrings[exSt++]);
  172. break;
  173. case TREPLACE_LSTRING:
  174. {
  175. std::string hlp;
  176. getLocalString(localStrings[loSt++], hlp);
  177. dst.replace(dst.find("%s"), 2, hlp);
  178. }
  179. break;
  180. case TREPLACE_NUMBER:
  181. dst.replace(dst.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  182. break;
  183. default:
  184. tlog1 << "MetaString processing error!\n";
  185. break;
  186. }
  187. }
  188. }
  189. static CGObjectInstance * createObject(int id, int subid, int3 pos, int owner)
  190. {
  191. CGObjectInstance * nobj;
  192. switch(id)
  193. {
  194. case HEROI_TYPE: //hero
  195. {
  196. CGHeroInstance * nobj = new CGHeroInstance();
  197. nobj->pos = pos;
  198. nobj->tempOwner = owner;
  199. nobj->subID = subid;
  200. //nobj->initHero(ran);
  201. return nobj;
  202. }
  203. case TOWNI_TYPE: //town
  204. nobj = new CGTownInstance;
  205. break;
  206. default: //rest of objects
  207. nobj = new CGObjectInstance;
  208. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  209. break;
  210. }
  211. nobj->ID = id;
  212. nobj->subID = subid;
  213. if(!nobj->defInfo)
  214. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  215. nobj->pos = pos;
  216. //nobj->state = NULL;//new CLuaObjectScript();
  217. nobj->tempOwner = owner;
  218. nobj->info = NULL;
  219. nobj->defInfo->id = id;
  220. nobj->defInfo->subid = subid;
  221. //assigning defhandler
  222. if(nobj->ID==HEROI_TYPE || nobj->ID==TOWNI_TYPE)
  223. return nobj;
  224. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  225. return nobj;
  226. }
  227. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  228. {
  229. for(unsigned int g=0; g<stacks.size(); ++g)
  230. {
  231. if(stacks[g]->ID == stackID && (!onlyAlive || stacks[g]->alive()))
  232. return stacks[g];
  233. }
  234. return NULL;
  235. }
  236. CStack * BattleInfo::getStackT(int tileID, bool onlyAlive)
  237. {
  238. for(unsigned int g=0; g<stacks.size(); ++g)
  239. {
  240. if(stacks[g]->position == tileID
  241. || (stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  242. || (stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  243. {
  244. if(!onlyAlive || stacks[g]->alive())
  245. {
  246. return stacks[g];
  247. }
  248. }
  249. }
  250. return NULL;
  251. }
  252. void BattleInfo::getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<int> & occupyable, bool flying, int stackToOmmit)
  253. {
  254. memset(accessibility, 1, BFIELD_SIZE); //initialize array with trues
  255. for(unsigned int g=0; g<stacks.size(); ++g)
  256. {
  257. if(!stacks[g]->alive() || stacks[g]->ID==stackToOmmit) //we don't want to lock position of this stack
  258. continue;
  259. accessibility[stacks[g]->position] = false;
  260. if(stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE)) //if it's a double hex creature
  261. {
  262. if(stacks[g]->attackerOwned)
  263. accessibility[stacks[g]->position-1] = false;
  264. else
  265. accessibility[stacks[g]->position+1] = false;
  266. }
  267. }
  268. //obstacles
  269. for(unsigned int b=0; b<obstacles.size(); ++b)
  270. {
  271. std::vector<int> blocked = VLC->heroh->obstacles[obstacles[b].ID].getBlocked(obstacles[b].pos);
  272. for(unsigned int c=0; c<blocked.size(); ++c)
  273. {
  274. if(blocked[c] >=0 && blocked[c] < BFIELD_SIZE)
  275. accessibility[blocked[c]] = false;
  276. }
  277. }
  278. if(addOccupiable && twoHex)
  279. {
  280. std::set<int> rem; //tiles to unlock
  281. for(int h=0; h<BFIELD_HEIGHT; ++h)
  282. {
  283. for(int w=1; w<BFIELD_WIDTH-1; ++w)
  284. {
  285. int hex = h * BFIELD_WIDTH + w;
  286. if(!isAccessible(hex, accessibility, twoHex, attackerOwned, flying, true)
  287. && (attackerOwned ? isAccessible(hex+1, accessibility, twoHex, attackerOwned, flying, true) : isAccessible(hex-1, accessibility, twoHex, attackerOwned, flying, true) )
  288. )
  289. rem.insert(hex);
  290. }
  291. }
  292. occupyable = rem;
  293. /*for(std::set<int>::const_iterator it = rem.begin(); it != rem.end(); ++it)
  294. {
  295. accessibility[*it] = true;
  296. }*/
  297. }
  298. }
  299. bool BattleInfo::isAccessible(int hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos)
  300. {
  301. if(flying && !lastPos)
  302. return true;
  303. if(twoHex)
  304. {
  305. //if given hex is accessible and appropriate adjacent one is free too
  306. return accessibility[hex] && accessibility[hex + (attackerOwned ? -1 : 1 )];
  307. }
  308. else
  309. {
  310. return accessibility[hex];
  311. }
  312. }
  313. void BattleInfo::makeBFS(int start, bool *accessibility, int *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying) //both pointers must point to the at least 187-elements int arrays
  314. {
  315. //inits
  316. for(int b=0; b<BFIELD_SIZE; ++b)
  317. predecessor[b] = -1;
  318. for(int g=0; g<BFIELD_SIZE; ++g)
  319. dists[g] = 100000000;
  320. std::queue<int> hexq; //bfs queue
  321. hexq.push(start);
  322. dists[hexq.front()] = 0;
  323. int curNext = -1; //for bfs loop only (helper var)
  324. while(!hexq.empty()) //bfs loop
  325. {
  326. int curHex = hexq.front();
  327. std::vector<int> neighbours = neighbouringTiles(curHex);
  328. hexq.pop();
  329. for(unsigned int nr=0; nr<neighbours.size(); nr++)
  330. {
  331. curNext = neighbours[nr]; //if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  332. if(!isAccessible(curNext, accessibility, twoHex, attackerOwned, flying, dists[curHex]+1 == dists[curNext]) || (dists[curHex]+1)>=dists[curNext])
  333. continue;
  334. hexq.push(curNext);
  335. dists[curNext] = dists[curHex] + 1;
  336. predecessor[curNext] = curHex;
  337. }
  338. }
  339. };
  340. std::vector<int> BattleInfo::getAccessibility(int stackID, bool addOccupiable)
  341. {
  342. std::vector<int> ret;
  343. bool ac[BFIELD_SIZE];
  344. CStack *s = getStack(stackID);
  345. std::set<int> occupyable;
  346. getAccessibilityMap(ac, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, addOccupiable, occupyable, s->hasFeatureOfType(StackFeature::FLYING), stackID);
  347. int pr[BFIELD_SIZE], dist[BFIELD_SIZE];
  348. makeBFS(s->position, ac, pr, dist, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, s->hasFeatureOfType(StackFeature::FLYING));
  349. if(s->hasFeatureOfType(StackFeature::DOUBLE_WIDE))
  350. {
  351. if(!addOccupiable)
  352. {
  353. std::vector<int> rem;
  354. for(int b=0; b<BFIELD_SIZE; ++b)
  355. {
  356. if( ac[b] && !(s->attackerOwned ? ac[b-1] : ac[b+1]))
  357. {
  358. rem.push_back(b);
  359. }
  360. }
  361. for(unsigned int g=0; g<rem.size(); ++g)
  362. {
  363. ac[rem[g]] = false;
  364. }
  365. //removing accessibility for side hexes
  366. for(int v=0; v<BFIELD_SIZE; ++v)
  367. if(s->attackerOwned ? (v%BFIELD_WIDTH)==1 : (v%BFIELD_WIDTH)==(BFIELD_WIDTH - 2))
  368. ac[v] = false;
  369. }
  370. }
  371. for(int i=0; i < BFIELD_SIZE ; ++i)
  372. if(
  373. ( ( !addOccupiable && dist[i] <= s->Speed() && ac[i] ) || ( addOccupiable && dist[i] <= s->Speed() && isAccessible(i, ac, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, s->hasFeatureOfType(StackFeature::FLYING), true) ) )//we can reach it
  374. || (vstd::contains(occupyable, i) && ( dist[ i + (s->attackerOwned ? 1 : -1 ) ] <= s->Speed() ) &&
  375. ac[i + (s->attackerOwned ? 1 : -1 )] ) //it's occupyable and we can reach adjacent hex
  376. )
  377. {
  378. ret.push_back(i);
  379. }
  380. return ret;
  381. }
  382. bool BattleInfo::isStackBlocked(int ID)
  383. {
  384. CStack *our = getStack(ID);
  385. for(unsigned int i=0; i<stacks.size();i++)
  386. {
  387. if( !stacks[i]->alive()
  388. || stacks[i]->owner==our->owner
  389. )
  390. continue; //we omit dead and allied stacks
  391. if(stacks[i]->hasFeatureOfType(StackFeature::DOUBLE_WIDE))
  392. {
  393. if( mutualPosition(stacks[i]->position, our->position) >= 0
  394. || mutualPosition(stacks[i]->position + (stacks[i]->attackerOwned ? -1 : 1), our->position) >= 0)
  395. return true;
  396. }
  397. else
  398. {
  399. if( mutualPosition(stacks[i]->position, our->position) >= 0 )
  400. return true;
  401. }
  402. }
  403. return false;
  404. }
  405. signed char BattleInfo::mutualPosition(int hex1, int hex2)
  406. {
  407. if(hex2 == hex1 - ( (hex1/17)%2 ? 18 : 17 )) //top left
  408. return 0;
  409. if(hex2 == hex1 - ( (hex1/17)%2 ? 17 : 16 )) //top right
  410. return 1;
  411. if(hex2 == hex1 - 1 && hex1%17 != 0) //left
  412. return 5;
  413. if(hex2 == hex1 + 1 && hex1%17 != 16) //right
  414. return 2;
  415. if(hex2 == hex1 + ( (hex1/17)%2 ? 16 : 17 )) //bottom left
  416. return 4;
  417. if(hex2 == hex1 + ( (hex1/17)%2 ? 17 : 18 )) //bottom right
  418. return 3;
  419. return -1;
  420. }
  421. std::vector<int> BattleInfo::neighbouringTiles(int hex)
  422. {
  423. #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);}
  424. std::vector<int> ret;
  425. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 18 : 17 ));
  426. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 17 : 16 ));
  427. CHECK_AND_PUSH(hex - 1);
  428. CHECK_AND_PUSH(hex + 1);
  429. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 16 : 17 ));
  430. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 17 : 18 ));
  431. #undef CHECK_AND_PUSH
  432. return ret;
  433. }
  434. std::pair< std::vector<int>, int > BattleInfo::getPath(int start, int dest, bool*accessibility, bool flyingCreature, bool twoHex, bool attackerOwned)
  435. {
  436. int predecessor[BFIELD_SIZE]; //for getting the Path
  437. int dist[BFIELD_SIZE]; //calculated distances
  438. makeBFS(start, accessibility, predecessor, dist, twoHex, attackerOwned, flyingCreature);
  439. if(predecessor[dest] == -1) //cannot reach destination
  440. {
  441. return std::make_pair(std::vector<int>(), 0);
  442. }
  443. //making the Path
  444. std::vector<int> path;
  445. int curElem = dest;
  446. while(curElem != start)
  447. {
  448. path.push_back(curElem);
  449. curElem = predecessor[curElem];
  450. }
  451. return std::make_pair(path, dist[dest]);
  452. }
  453. int CStack::valOfFeatures(StackFeature::ECombatFeatures type, int subtype) const
  454. {
  455. int ret = 0;
  456. if(subtype == -1024) //any subtype
  457. {
  458. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  459. if(i->type == type)
  460. ret += i->value;
  461. }
  462. else //given subtype
  463. {
  464. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  465. if(i->type == type && i->subtype == subtype)
  466. ret += i->value;
  467. }
  468. return ret;
  469. }
  470. bool CStack::hasFeatureOfType(StackFeature::ECombatFeatures type, int subtype) const
  471. {
  472. if(subtype == -1024) //any subtype
  473. {
  474. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  475. if(i->type == type)
  476. return true;
  477. }
  478. else //given subtype
  479. {
  480. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  481. if(i->type == type && i->subtype == subtype)
  482. return true;
  483. }
  484. return false;
  485. }
  486. CStack::CStack(CCreature * C, int A, int O, int I, bool AO, int S)
  487. :ID(I), creature(C), amount(A), baseAmount(A), firstHPleft(C->hitPoints), owner(O), slot(S), attackerOwned(AO), position(-1),
  488. counterAttacks(1), shots(C->shots), features(C->abilities)
  489. {
  490. state.insert(ALIVE);
  491. }
  492. ui32 CStack::Speed() const
  493. {
  494. if(hasFeatureOfType(StackFeature::SIEGE_WEAPON)) //war machnes cannot move
  495. return 0;
  496. int speed = creature->speed;
  497. speed += valOfFeatures(StackFeature::SPEED_BONUS);
  498. int percentBonus = 0;
  499. for(int g=0; g<features.size(); ++g)
  500. {
  501. if(features[g].type == StackFeature::SPEED_BONUS)
  502. {
  503. percentBonus += features[g].additionalInfo;
  504. }
  505. }
  506. if(percentBonus < 0)
  507. {
  508. speed = (abs(percentBonus) * speed)/100;
  509. }
  510. else
  511. {
  512. speed = ((100 + percentBonus) * speed)/100;
  513. }
  514. //bind effect check
  515. if(getEffect(72))
  516. {
  517. return 0;
  518. }
  519. return speed;
  520. }
  521. const CStack::StackEffect * CStack::getEffect(ui16 id) const
  522. {
  523. for (unsigned int i=0; i< effects.size(); i++)
  524. if(effects[i].id == id)
  525. return &effects[i];
  526. return NULL;
  527. }
  528. ui8 CStack::howManyEffectsSet(ui16 id) const
  529. {
  530. ui8 ret = 0;
  531. for (unsigned int i=0; i< effects.size(); i++)
  532. if(effects[i].id == id) //effect found
  533. {
  534. ++ret;
  535. }
  536. return ret;
  537. }
  538. si8 CStack::Morale() const
  539. {
  540. si8 ret = morale;
  541. if(hasFeatureOfType(StackFeature::NON_LIVING) || hasFeatureOfType(StackFeature::UNDEAD) || hasFeatureOfType(StackFeature::NO_MORALE))
  542. return 0;
  543. ret += valOfFeatures(StackFeature::MORALE_BONUS); //mirth & sorrow & other
  544. if(hasFeatureOfType(StackFeature::SELF_MORALE)) //eg. minotaur
  545. {
  546. ret = std::max<si8>(ret, +1);
  547. }
  548. if(ret > 3) ret = 3;
  549. if(ret < -3) ret = -3;
  550. return ret;
  551. }
  552. si8 CStack::Luck() const
  553. {
  554. si8 ret = luck;
  555. if(hasFeatureOfType(StackFeature::NO_LUCK))
  556. return 0;
  557. ret += valOfFeatures(StackFeature::LUCK_BONUS); //fortune & misfortune & other
  558. if(hasFeatureOfType(StackFeature::SELF_LUCK)) //eg. halfling
  559. {
  560. ret = std::max<si8>(ret, +1);
  561. }
  562. if(ret > 3) ret = 3;
  563. if(ret < -3) ret = -3;
  564. return ret;
  565. }
  566. si32 CStack::Attack() const
  567. {
  568. si32 ret = creature->attack; //value to be returned
  569. if(hasFeatureOfType(StackFeature::IN_FRENZY)) //frenzy for attacker
  570. {
  571. ret += (VLC->spellh->spells[56].powers[getEffect(56)->level]/100.0) * Defense(false);
  572. }
  573. ret += valOfFeatures(StackFeature::ATTACK_BONUS);
  574. return ret;
  575. }
  576. si32 CStack::Defense(bool withFrenzy /*= true*/) const
  577. {
  578. si32 ret = creature->defence;
  579. if(withFrenzy && getEffect(56)) //frenzy for defender
  580. {
  581. return 0;
  582. }
  583. ret += valOfFeatures(StackFeature::DEFENCE_BONUS);
  584. return ret;
  585. }
  586. ui16 CStack::MaxHealth() const
  587. {
  588. return creature->hitPoints + valOfFeatures(StackFeature::HP_BONUS);
  589. }
  590. bool CStack::willMove()
  591. {
  592. return !vstd::contains(state, DEFENDING)
  593. && !vstd::contains(state, MOVED)
  594. && alive()
  595. && ! hasFeatureOfType(StackFeature::NOT_ACTIVE); //eg. Ammo Cart
  596. }
  597. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native, int player, const CTown *town, std::map<ui32,CGHeroInstance *> &available) const
  598. {
  599. CGHeroInstance *ret = NULL;
  600. if(player<0 || player>=PLAYER_LIMIT)
  601. {
  602. tlog1 << "Cannot pick hero for " << town->Name() << ". Wrong owner!\n";
  603. return NULL;
  604. }
  605. std::vector<CGHeroInstance *> pool;
  606. if(native)
  607. {
  608. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  609. {
  610. if(pavailable.find(i->first)->second & 1<<player
  611. && i->second->type->heroType/2 == town->typeID)
  612. {
  613. pool.push_back(i->second);
  614. }
  615. }
  616. if(!pool.size())
  617. {
  618. tlog1 << "Cannot pick native hero for " << player << ". Picking any...\n";
  619. return pickHeroFor(false, player, town, available);
  620. }
  621. else
  622. {
  623. ret = pool[rand()%pool.size()];
  624. }
  625. }
  626. else
  627. {
  628. int sum=0, r;
  629. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  630. {
  631. if(pavailable.find(i->first)->second & 1<<player)
  632. {
  633. pool.push_back(i->second);
  634. sum += i->second->type->heroClass->selectionProbability[town->typeID];
  635. }
  636. }
  637. if(!pool.size())
  638. {
  639. tlog1 << "There are no heroes available for player " << player<<"!\n";
  640. return NULL;
  641. }
  642. r = rand()%sum;
  643. for(unsigned int i=0; i<pool.size(); i++)
  644. {
  645. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  646. if(r<0)
  647. ret = pool[i];
  648. }
  649. if(!ret)
  650. ret = pool.back();
  651. }
  652. available.erase(ret->subID);
  653. return ret;
  654. }
  655. //void CGameState::apply(CPack * pack)
  656. //{
  657. // while(!mx->try_lock())
  658. // boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  659. // //applyNL(pack);
  660. // mx->unlock();
  661. //}
  662. int CGameState::pickHero(int owner)
  663. {
  664. int h=-1;
  665. if(!map->getHero(h = scenarioOps->getIthPlayersSettings(owner).hero,0) && h>=0) //we haven't used selected hero
  666. return h;
  667. int f = scenarioOps->getIthPlayersSettings(owner).castle;
  668. int i=0;
  669. do //try to find free hero of our faction
  670. {
  671. i++;
  672. h = scenarioOps->getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  673. } while( map->getHero(h) && i<175);
  674. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  675. {
  676. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  677. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  678. if(!map->getHero(j))
  679. h=j;
  680. }
  681. return h;
  682. }
  683. CGHeroInstance *CGameState::getHero(int objid)
  684. {
  685. if(objid<0 || objid>=map->objects.size() || map->objects[objid]->ID!=34)
  686. return NULL;
  687. return static_cast<CGHeroInstance *>(map->objects[objid]);
  688. }
  689. CGTownInstance *CGameState::getTown(int objid)
  690. {
  691. if(objid<0 || objid>=map->objects.size())
  692. return NULL;
  693. return static_cast<CGTownInstance *>(map->objects[objid]);
  694. }
  695. std::pair<int,int> CGameState::pickObject(CGObjectInstance *obj)
  696. {
  697. switch(obj->ID)
  698. {
  699. case 65: //random artifact
  700. return std::pair<int,int>(5,(ran()%136)+7); //tylko sensowny zakres - na poczatku sa katapulty itp, na koncu specjalne i blanki
  701. case 66: //random treasure artifact
  702. return std::pair<int,int>(5,VLC->arth->treasures[ran()%VLC->arth->treasures.size()]->id);
  703. case 67: //random minor artifact
  704. return std::pair<int,int>(5,VLC->arth->minors[ran()%VLC->arth->minors.size()]->id);
  705. case 68: //random major artifact
  706. return std::pair<int,int>(5,VLC->arth->majors[ran()%VLC->arth->majors.size()]->id);
  707. case 69: //random relic artifact
  708. return std::pair<int,int>(5,VLC->arth->relics[ran()%VLC->arth->relics.size()]->id);
  709. case 70: //random hero
  710. {
  711. return std::pair<int,int>(HEROI_TYPE,pickHero(obj->tempOwner));
  712. }
  713. case 71: //random monster
  714. {
  715. int r;
  716. do
  717. {
  718. r = ran()%197;
  719. } while (vstd::contains(VLC->creh->notUsedMonsters,r));
  720. return std::pair<int,int>(54,r);
  721. }
  722. case 72: //random monster lvl1
  723. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  724. case 73: //random monster lvl2
  725. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  726. case 74: //random monster lvl3
  727. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  728. case 75: //random monster lvl4
  729. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  730. case 76: //random resource
  731. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  732. case 77: //random town
  733. {
  734. int align = (static_cast<CGTownInstance*>(obj))->alignment,
  735. f;
  736. if(align>PLAYER_LIMIT-1)//same as owner / random
  737. {
  738. if(obj->tempOwner > PLAYER_LIMIT-1)
  739. f = -1; //random
  740. else
  741. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  742. }
  743. else
  744. {
  745. f = scenarioOps->getIthPlayersSettings(align).castle;
  746. }
  747. if(f<0) f = ran()%VLC->townh->towns.size();
  748. return std::pair<int,int>(TOWNI_TYPE,f);
  749. }
  750. case 162: //random monster lvl5
  751. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  752. case 163: //random monster lvl6
  753. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  754. case 164: //random monster lvl7
  755. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  756. case 216: //random dwelling
  757. {
  758. int faction = ran()%F_NUMBER;
  759. CCreGen2ObjInfo* info = static_cast<CCreGen2ObjInfo*>(obj->info);
  760. if (info->asCastle)
  761. {
  762. for(unsigned int i=0;i<map->objects.size();i++)
  763. {
  764. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  765. {
  766. randomizeObject(map->objects[i]); //we have to randomize the castle first
  767. faction = map->objects[i]->subID;
  768. break;
  769. }
  770. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  771. {
  772. faction = map->objects[i]->subID;
  773. break;
  774. }
  775. }
  776. }
  777. else
  778. {
  779. while((!(info->castles[0]&(1<<faction))))
  780. {
  781. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  782. break;
  783. faction = ran()%F_NUMBER;
  784. }
  785. }
  786. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  787. int cid = VLC->townh->towns[faction].basicCreatures[level];
  788. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  789. if(VLC->objh->cregens[i]==cid)
  790. return std::pair<int,int>(17,i);
  791. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  792. return std::pair<int,int>(17,0);
  793. }
  794. case 217:
  795. {
  796. int faction = ran()%F_NUMBER;
  797. CCreGenObjInfo* info = static_cast<CCreGenObjInfo*>(obj->info);
  798. if (info->asCastle)
  799. {
  800. for(unsigned int i=0;i<map->objects.size();i++)
  801. {
  802. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  803. {
  804. randomizeObject(map->objects[i]); //we have to randomize the castle first
  805. faction = map->objects[i]->subID;
  806. break;
  807. }
  808. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  809. {
  810. faction = map->objects[i]->subID;
  811. break;
  812. }
  813. }
  814. }
  815. else
  816. {
  817. while((!(info->castles[0]&(1<<faction))))
  818. {
  819. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  820. break;
  821. faction = ran()%F_NUMBER;
  822. }
  823. }
  824. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  825. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  826. if(VLC->objh->cregens[i]==cid)
  827. return std::pair<int,int>(17,i);
  828. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  829. return std::pair<int,int>(17,0);
  830. }
  831. case 218:
  832. {
  833. CCreGen3ObjInfo* info = static_cast<CCreGen3ObjInfo*>(obj->info);
  834. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  835. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  836. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  837. if(VLC->objh->cregens[i]==cid)
  838. return std::pair<int,int>(17,i);
  839. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  840. return std::pair<int,int>(17,0);
  841. }
  842. }
  843. return std::pair<int,int>(-1,-1);
  844. }
  845. void CGameState::randomizeObject(CGObjectInstance *cur)
  846. {
  847. std::pair<int,int> ran = pickObject(cur);
  848. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  849. {
  850. if(cur->ID==TOWNI_TYPE) //town - set def
  851. {
  852. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  853. if(t->hasCapitol())
  854. t->defInfo = capitols[t->subID];
  855. else if(t->hasFort())
  856. t->defInfo = forts[t->subID];
  857. else
  858. t->defInfo = villages[t->subID];
  859. }
  860. return;
  861. }
  862. else if(ran.first==HEROI_TYPE)//special code for hero
  863. {
  864. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  865. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  866. cur->ID = ran.first;
  867. h->portrait = cur->subID = ran.second;
  868. h->type = VLC->heroh->heroes[ran.second];
  869. map->heroes.push_back(h);
  870. return; //TODO: maybe we should do something with definfo?
  871. }
  872. else if(ran.first==TOWNI_TYPE)//special code for town
  873. {
  874. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  875. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  876. cur->ID = ran.first;
  877. cur->subID = ran.second;
  878. t->town = &VLC->townh->towns[ran.second];
  879. if(t->hasCapitol())
  880. t->defInfo = capitols[t->subID];
  881. else if(t->hasFort())
  882. t->defInfo = forts[t->subID];
  883. else
  884. t->defInfo = villages[t->subID];
  885. map->towns.push_back(t);
  886. return;
  887. }
  888. //we have to replace normal random object
  889. cur->ID = ran.first;
  890. cur->subID = ran.second;
  891. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  892. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  893. if(!cur->defInfo)
  894. {
  895. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  896. return;
  897. }
  898. map->addBlockVisTiles(cur);
  899. }
  900. int CGameState::getDate(int mode) const
  901. {
  902. int temp;
  903. switch (mode)
  904. {
  905. case 0:
  906. return day;
  907. break;
  908. case 1:
  909. temp = (day)%7;
  910. if (temp)
  911. return temp;
  912. else return 7;
  913. break;
  914. case 2:
  915. temp = ((day-1)/7)+1;
  916. if (!(temp%4))
  917. return 4;
  918. else
  919. return (temp%4);
  920. break;
  921. case 3:
  922. return ((day-1)/28)+1;
  923. break;
  924. }
  925. return 0;
  926. }
  927. CGameState::CGameState()
  928. {
  929. mx = new boost::shared_mutex();
  930. map = NULL;
  931. curB = NULL;
  932. scenarioOps = NULL;
  933. applierGs = new CGSApplier;
  934. }
  935. CGameState::~CGameState()
  936. {
  937. delete mx;
  938. delete map;
  939. delete curB;
  940. delete scenarioOps;
  941. delete applierGs;
  942. }
  943. void CGameState::init(StartInfo * si, Mapa * map, int Seed)
  944. {
  945. day = 0;
  946. seed = Seed;
  947. ran.seed((boost::int32_t)seed);
  948. scenarioOps = si;
  949. this->map = map;
  950. loadTownDInfos();
  951. //picking random factions for players
  952. for(unsigned int i=0;i<scenarioOps->playerInfos.size();i++)
  953. {
  954. if(scenarioOps->playerInfos[i].castle==-1)
  955. {
  956. int f;
  957. do
  958. {
  959. f = ran()%F_NUMBER;
  960. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  961. scenarioOps->playerInfos[i].castle = f;
  962. }
  963. }
  964. //randomizing objects
  965. for(unsigned int no=0; no<map->objects.size(); ++no)
  966. {
  967. randomizeObject(map->objects[no]);
  968. if(map->objects[no]->ID==26)
  969. {
  970. map->objects[no]->defInfo->handler=NULL;
  971. }
  972. map->objects[no]->hoverName = VLC->generaltexth->names[map->objects[no]->ID];
  973. }
  974. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  975. /*********give starting hero****************************************/
  976. for(int i=0;i<PLAYER_LIMIT;i++)
  977. {
  978. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==CMapHeader::RoE))
  979. {
  980. int3 hpos = map->players[i].posOfMainTown;
  981. hpos.x+=1;// hpos.y+=1;
  982. int j;
  983. for(j=0; j<scenarioOps->playerInfos.size(); j++) //don't add unsigned here - we are refering to the variable above
  984. if(scenarioOps->playerInfos[j].color == i)
  985. break;
  986. if(j == scenarioOps->playerInfos.size())
  987. continue;
  988. int h=pickHero(i);
  989. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(HEROI_TYPE,h,hpos,i));
  990. nnn->id = map->objects.size();
  991. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  992. for(unsigned int o=0;o<map->towns.size();o++) //find main town
  993. {
  994. if(map->towns[o]->pos == hpos)
  995. {
  996. map->towns[o]->visitingHero = nnn;
  997. nnn->visitedTown = map->towns[o];
  998. nnn->inTownGarrison = false;
  999. break;
  1000. }
  1001. }
  1002. nnn->initHero();
  1003. map->heroes.push_back(nnn);
  1004. map->objects.push_back(nnn);
  1005. map->addBlockVisTiles(nnn);
  1006. }
  1007. }
  1008. /*********creating players entries in gs****************************************/
  1009. for (unsigned int i=0; i<scenarioOps->playerInfos.size();i++)
  1010. {
  1011. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  1012. ins.second.color=ins.first;
  1013. ins.second.serial=i;
  1014. ins.second.human = scenarioOps->playerInfos[i].human;
  1015. players.insert(ins);
  1016. }
  1017. /******************RESOURCES****************************************************/
  1018. //TODO: computer player should receive other amount of resource than computer (depending on difficulty)
  1019. std::vector<int> startres;
  1020. std::ifstream tis("config/startres.txt");
  1021. int k;
  1022. for (int j=0;j<scenarioOps->difficulty;j++)
  1023. {
  1024. tis >> k;
  1025. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1026. tis>>k;
  1027. }
  1028. tis >> k;
  1029. for (int i=0;i<RESOURCE_QUANTITY;i++)
  1030. {
  1031. tis >> k;
  1032. startres.push_back(k);
  1033. }
  1034. tis.close();
  1035. tis.clear();
  1036. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1037. {
  1038. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1039. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1040. (*i).second.resources[x] = startres[x];
  1041. }
  1042. tis.open("config/resources.txt");
  1043. tis >> k;
  1044. int pom;
  1045. for(int i=0;i<k;i++)
  1046. {
  1047. tis >> pom;
  1048. resVals.push_back(pom);
  1049. }
  1050. /*************************HEROES************************************************/
  1051. std::set<int> hids;
  1052. for(unsigned int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1053. if(map->allowedHeroes[i])
  1054. hids.insert(i);
  1055. for (unsigned int i=0; i<map->heroes.size();i++) //heroes instances initialization
  1056. {
  1057. if (map->heroes[i]->getOwner()<0)
  1058. {
  1059. tlog2 << "Warning - hero with uninitialized owner!\n";
  1060. continue;
  1061. }
  1062. CGHeroInstance * vhi = (map->heroes[i]);
  1063. vhi->initHero();
  1064. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1065. hids.erase(vhi->subID);
  1066. }
  1067. for(unsigned int i=0; i<map->predefinedHeroes.size(); i++)
  1068. {
  1069. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1070. continue;
  1071. map->predefinedHeroes[i]->initHero();
  1072. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1073. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1074. hids.erase(map->predefinedHeroes[i]->subID);
  1075. }
  1076. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go into the pool
  1077. {
  1078. CGHeroInstance * vhi = new CGHeroInstance();
  1079. vhi->initHero(hid);
  1080. hpool.heroesPool[hid] = vhi;
  1081. hpool.pavailable[hid] = 0xff;
  1082. }
  1083. for(unsigned int i=0; i<map->disposedHeroes.size(); i++)
  1084. {
  1085. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1086. }
  1087. /*************************FOG**OF**WAR******************************************/
  1088. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1089. {
  1090. k->second.fogOfWarMap.resize(map->width);
  1091. for(int g=0; g<map->width; ++g)
  1092. k->second.fogOfWarMap[g].resize(map->height);
  1093. for(int g=-0; g<map->width; ++g)
  1094. for(int h=0; h<map->height; ++h)
  1095. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1096. for(int g=0; g<map->width; ++g)
  1097. for(int h=0; h<map->height; ++h)
  1098. for(int v=0; v<map->twoLevel+1; ++v)
  1099. k->second.fogOfWarMap[g][h][v] = 0;
  1100. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1101. {
  1102. if(obj->tempOwner != k->first) continue; //not a flagged object
  1103. int3 objCenter = obj->getSightCenter();
  1104. int radious = obj->getSightRadious();
  1105. for (int xd = std::max<int>(objCenter.x - radious , 0); xd <= std::min<int>(objCenter.x + radious, map->width - 1); xd++)
  1106. {
  1107. for (int yd = std::max<int>(objCenter.y - radious, 0); yd <= std::min<int>(objCenter.y + radious, map->height - 1); yd++)
  1108. {
  1109. double distance = objCenter.dist2d(int3(xd,yd,objCenter.z)) - 0.5;
  1110. if(distance <= radious)
  1111. k->second.fogOfWarMap[xd][yd][objCenter.z] = 1;
  1112. }
  1113. }
  1114. }
  1115. //for(int xd=0; xd<map->width; ++xd) //revealing part of map around heroes
  1116. //{
  1117. // for(int yd=0; yd<map->height; ++yd)
  1118. // {
  1119. // for(int ch=0; ch<k->second.heroes.size(); ++ch)
  1120. // {
  1121. // int deltaX = (k->second.heroes[ch]->getPosition(false).x-xd)*(k->second.heroes[ch]->getPosition(false).x-xd);
  1122. // int deltaY = (k->second.heroes[ch]->getPosition(false).y-yd)*(k->second.heroes[ch]->getPosition(false).y-yd);
  1123. // if(deltaX+deltaY<k->second.heroes[ch]->getSightDistance()*k->second.heroes[ch]->getSightDistance())
  1124. // k->second.fogOfWarMap[xd][yd][k->second.heroes[ch]->getPosition(false).z] = 1;
  1125. // }
  1126. // }
  1127. //}
  1128. //starting bonus
  1129. if(si->playerInfos[k->second.serial].bonus==brandom)
  1130. si->playerInfos[k->second.serial].bonus = ran()%3;
  1131. switch(si->playerInfos[k->second.serial].bonus)
  1132. {
  1133. case bgold:
  1134. k->second.resources[6] += 500 + (ran()%6)*100;
  1135. break;
  1136. case bresource:
  1137. {
  1138. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1139. if(res == 127)
  1140. {
  1141. k->second.resources[0] += 5 + ran()%6;
  1142. k->second.resources[2] += 5 + ran()%6;
  1143. }
  1144. else
  1145. {
  1146. k->second.resources[res] += 3 + ran()%4;
  1147. }
  1148. break;
  1149. }
  1150. case bartifact:
  1151. {
  1152. if(!k->second.heroes.size())
  1153. {
  1154. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1155. break;
  1156. }
  1157. CArtifact *toGive;
  1158. do
  1159. {
  1160. toGive = VLC->arth->treasures[ran() % VLC->arth->treasures.size()];
  1161. } while (!map->allowedArtifact[toGive->id]);
  1162. CGHeroInstance *hero = k->second.heroes[0];
  1163. std::vector<ui16>::iterator slot = vstd::findFirstNot(hero->artifWorn,toGive->possibleSlots);
  1164. if(slot!=toGive->possibleSlots.end())
  1165. {
  1166. hero->artifWorn[*slot] = toGive->id;
  1167. hero->recreateArtBonuses();
  1168. }
  1169. else
  1170. hero->artifacts.push_back(toGive->id);
  1171. }
  1172. }
  1173. }
  1174. /****************************TOWNS************************************************/
  1175. for (unsigned int i=0;i<map->towns.size();i++)
  1176. {
  1177. CGTownInstance * vti =(map->towns[i]);
  1178. if(!vti->town)
  1179. vti->town = &VLC->townh->towns[vti->subID];
  1180. if (vti->name.length()==0) // if town hasn't name we draw it
  1181. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1182. //init buildings
  1183. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1184. {
  1185. vti->builtBuildings.erase(-50);
  1186. vti->builtBuildings.insert(10);
  1187. vti->builtBuildings.insert(5);
  1188. vti->builtBuildings.insert(30);
  1189. if(ran()%2)
  1190. vti->builtBuildings.insert(31);
  1191. }
  1192. //init spells
  1193. vti->spells.resize(SPELL_LEVELS);
  1194. CSpell *s;
  1195. for(unsigned int z=0; z<vti->obligatorySpells.size();z++)
  1196. {
  1197. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1198. vti->spells[s->level-1].push_back(s->id);
  1199. vti->possibleSpells -= s->id;
  1200. }
  1201. while(vti->possibleSpells.size())
  1202. {
  1203. ui32 total=0, sel=-1;
  1204. for(unsigned int ps=0;ps<vti->possibleSpells.size();ps++)
  1205. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1206. int r = (total)? ran()%total : -1;
  1207. for(unsigned int ps=0; ps<vti->possibleSpells.size();ps++)
  1208. {
  1209. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1210. if(r<0)
  1211. {
  1212. sel = ps;
  1213. break;
  1214. }
  1215. }
  1216. if(sel<0)
  1217. sel=0;
  1218. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1219. vti->spells[s->level-1].push_back(s->id);
  1220. vti->possibleSpells -= s->id;
  1221. }
  1222. //init garrisons
  1223. for (std::map<si32,std::pair<ui32,si32> >::iterator j=vti->army.slots.begin(); j!=vti->army.slots.end();j++)
  1224. {
  1225. if(j->second.first > 196 && j->second.first < 211)
  1226. {
  1227. if(j->second.first%2)
  1228. j->second.first = vti->town->basicCreatures[ (j->second.first-197) / 2 ];
  1229. else
  1230. j->second.first = vti->town->upgradedCreatures[ (j->second.first-197) / 2 ];
  1231. }
  1232. }
  1233. if(vti->getOwner() != 255)
  1234. getPlayer(vti->getOwner())->towns.push_back(vti);
  1235. }
  1236. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1237. {
  1238. if(k->first==-1 || k->first==255)
  1239. continue;
  1240. //init visiting and garrisoned heroes
  1241. for(unsigned int l=0; l<k->second.heroes.size();l++)
  1242. {
  1243. for(unsigned int m=0; m<k->second.towns.size();m++)
  1244. {
  1245. int3 vistile = k->second.towns[m]->pos; vistile.x--; //tile next to the entrance
  1246. if(vistile == k->second.heroes[l]->pos || k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1247. {
  1248. k->second.towns[m]->visitingHero = k->second.heroes[l];
  1249. k->second.heroes[l]->visitedTown = k->second.towns[m];
  1250. k->second.heroes[l]->inTownGarrison = false;
  1251. if(k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1252. k->second.heroes[l]->pos.x -= 1;
  1253. break;
  1254. }
  1255. }
  1256. }
  1257. }
  1258. for(unsigned int i=0; i<map->defy.size(); i++)
  1259. {
  1260. map->defy[i]->serial = i;
  1261. }
  1262. for(unsigned int i=0; i<map->objects.size(); i++)
  1263. {
  1264. map->objects[i]->initObj();
  1265. if(map->objects[i]->ID == 62) //prison also needs to initialize hero
  1266. static_cast<CGHeroInstance*>(map->objects[i])->initHero();
  1267. }
  1268. }
  1269. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1270. {
  1271. return true;
  1272. }
  1273. int CGameState::battleGetStack(int pos, bool onlyAlive)
  1274. {
  1275. if(!curB)
  1276. return -1;
  1277. for(unsigned int g=0; g<curB->stacks.size(); ++g)
  1278. {
  1279. if((curB->stacks[g]->position == pos
  1280. || (curB->stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE)
  1281. &&( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos)
  1282. || (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos) )
  1283. ))
  1284. && (!onlyAlive || curB->stacks[g]->alive())
  1285. )
  1286. return curB->stacks[g]->ID;
  1287. }
  1288. return -1;
  1289. }
  1290. int CGameState::battleGetBattlefieldType(int3 tile)
  1291. {
  1292. if(tile==int3() && curB)
  1293. tile = curB->tile;
  1294. else if(tile==int3() && !curB)
  1295. return -1;
  1296. const std::vector <CGObjectInstance*> & objs = map->objects;
  1297. for(int g=0; g<objs.size(); ++g)
  1298. {
  1299. if( !objs[g] || objs[g]->pos.x - tile.x < 0 || objs[g]->pos.x - tile.x >= 8
  1300. || tile.y - objs[g]->pos.y + 5 < 0 || tile.y - objs[g]->pos.y + 5 >=6
  1301. || !objs[g]->coveringAt(objs[g]->pos.x - tile.x, tile.y - objs[g]->pos.y + 5)
  1302. ) //look only for objects covering given tile
  1303. continue;
  1304. switch(objs[g]->ID)
  1305. {
  1306. case 222: //clover field
  1307. return 19;
  1308. case 21: case 223: //cursed ground
  1309. return 22;
  1310. case 224: //evil fog
  1311. return 20;
  1312. case 225: //favourable winds
  1313. return 21;
  1314. case 226: //fiery fields
  1315. return 14;
  1316. case 227: //holy ground
  1317. return 18;
  1318. case 228: //lucid pools
  1319. return 17;
  1320. case 229: //magic clouds
  1321. return 16;
  1322. case 46: case 230: //magic plains
  1323. return 9;
  1324. case 231: //rocklands
  1325. return 15;
  1326. }
  1327. }
  1328. switch(map->terrain[tile.x][tile.y][tile.z].tertype)
  1329. {
  1330. case TerrainTile::dirt:
  1331. return rand()%3+3;
  1332. case TerrainTile::sand:
  1333. return 2; //TODO: coast support
  1334. case TerrainTile::grass:
  1335. return rand()%2+6;
  1336. case TerrainTile::snow:
  1337. return rand()%2+10;
  1338. case TerrainTile::swamp:
  1339. return 13;
  1340. case TerrainTile::rough:
  1341. return 23;
  1342. case TerrainTile::subterranean:
  1343. return 12;
  1344. case TerrainTile::lava:
  1345. return 8;
  1346. case TerrainTile::water:
  1347. return 25;
  1348. case TerrainTile::rock:
  1349. return 15;
  1350. default:
  1351. return -1;
  1352. }
  1353. }
  1354. UpgradeInfo CGameState::getUpgradeInfo(CArmedInstance *obj, int stackPos)
  1355. {
  1356. UpgradeInfo ret;
  1357. CCreature *base = &VLC->creh->creatures[obj->army.slots[stackPos].first];
  1358. if((obj->ID == TOWNI_TYPE) || ((obj->ID == HEROI_TYPE) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
  1359. {
  1360. CGTownInstance * t;
  1361. if(obj->ID == TOWNI_TYPE)
  1362. t = static_cast<CGTownInstance *>(const_cast<CArmedInstance *>(obj));
  1363. else
  1364. t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
  1365. for(std::set<si32>::iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++)
  1366. {
  1367. if( (*i) >= 37 && (*i) < 44 ) //upgraded creature dwelling
  1368. {
  1369. int nid = t->town->upgradedCreatures[(*i)-37]; //upgrade offered by that building
  1370. if(base->upgrades.find(nid) != base->upgrades.end()) //possible upgrade
  1371. {
  1372. ret.newID.push_back(nid);
  1373. ret.cost.push_back(std::set<std::pair<int,int> >());
  1374. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1375. {
  1376. int dif = VLC->creh->creatures[nid].cost[j] - base->cost[j];
  1377. if(dif)
  1378. ret.cost[ret.cost.size()-1].insert(std::make_pair(j,dif));
  1379. }
  1380. }
  1381. }
  1382. }//end for
  1383. }
  1384. //TODO: check if hero ability makes some upgrades possible
  1385. if(ret.newID.size())
  1386. ret.oldID = base->idNumber;
  1387. return ret;
  1388. }
  1389. float CGameState::getMarketEfficiency( int player, int mode/*=0*/ )
  1390. {
  1391. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1392. if(mode) return -1; //todo - support other modes
  1393. int mcount = 0;
  1394. for(unsigned int i=0;i<getPlayer(player)->towns.size();i++)
  1395. if(vstd::contains(getPlayer(player)->towns[i]->builtBuildings,14))
  1396. mcount++;
  1397. float ret = std::min(((float)mcount+1.0f)/20.0f,0.5f);
  1398. return ret;
  1399. }
  1400. void CGameState::loadTownDInfos()
  1401. {
  1402. for(int i=0;i<F_NUMBER;i++)
  1403. {
  1404. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1405. forts[i] = VLC->dobjinfo->castles[i];
  1406. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1407. }
  1408. }
  1409. void CGameState::getNeighbours(int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand)
  1410. {
  1411. int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1412. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1413. vec.clear();
  1414. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1415. {
  1416. int3 hlp = tile + dirs[i];
  1417. if(!map->isInTheMap(hlp))
  1418. continue;
  1419. if((indeterminate(onLand) || onLand == (map->getTile(hlp).tertype!=8) )
  1420. && map->getTile(hlp).tertype!=9)
  1421. {
  1422. vec.push_back(hlp);
  1423. }
  1424. }
  1425. }
  1426. int CGameState::getMovementCost(const CGHeroInstance *h, int3 src, int3 dest, int remainingMovePoints, bool checkLast)
  1427. {
  1428. if(src == dest) //same tile
  1429. return 0;
  1430. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1431. &d = map->terrain[dest.x][dest.y][dest.z];
  1432. //get basic cost
  1433. int ret = h->getTileCost(d,s);
  1434. if(src.x!=dest.x && src.y!=dest.y) //it's diagonal move
  1435. {
  1436. int old = ret;
  1437. ret *= 1.414;
  1438. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1439. if(ret > remainingMovePoints && remainingMovePoints > old)
  1440. {
  1441. return remainingMovePoints;
  1442. }
  1443. }
  1444. int left = remainingMovePoints-ret;
  1445. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1446. {
  1447. std::vector<int3> vec;
  1448. getNeighbours(dest, vec, s.tertype != TerrainTile::water);
  1449. for(size_t i=0; i < vec.size(); i++)
  1450. {
  1451. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1452. if(fcost <= left)
  1453. {
  1454. return ret;
  1455. }
  1456. }
  1457. ret = remainingMovePoints;
  1458. }
  1459. return ret;
  1460. }
  1461. int CGameState::canBuildStructure( const CGTownInstance *t, int ID )
  1462. {
  1463. int ret = 7; //allowed by default
  1464. //checking resources
  1465. CBuilding * pom = VLC->buildh->buildings[t->subID][ID];
  1466. if(!pom)return 8;
  1467. if(pom->Name().size()==0||pom->resources.size()==0)return 2;//TODO: why does this happen?
  1468. for(int res=0;res<pom->resources.size();res++) //TODO: support custom amount of resources
  1469. {
  1470. if(pom->resources[res] > getPlayer(t->tempOwner)->resources[res])
  1471. ret = 6; //lack of res
  1472. }
  1473. //checking for requirements
  1474. for( std::set<int>::iterator ri = VLC->townh->requirements[t->subID][ID].begin();
  1475. ri != VLC->townh->requirements[t->subID][ID].end();
  1476. ri++ )
  1477. {
  1478. if(t->builtBuildings.find(*ri)==t->builtBuildings.end())
  1479. ret = 8; //lack of requirements - cannot build
  1480. }
  1481. //can we build it?
  1482. if(t->forbiddenBuildings.find(ID)!=t->forbiddenBuildings.end())
  1483. ret = 2; //forbidden
  1484. else if(t->builded >= MAX_BUILDING_PER_TURN)
  1485. ret = 5; //building limit
  1486. if(ID == 13) //capitol
  1487. {
  1488. for(unsigned int in = 0; in < map->towns.size(); in++)
  1489. {
  1490. if(map->towns[in]->tempOwner==t->tempOwner && vstd::contains(map->towns[in]->builtBuildings,13))
  1491. {
  1492. ret = 0; //no more than one capitol
  1493. break;
  1494. }
  1495. }
  1496. }
  1497. else if(ID == 6) //shipyard
  1498. {
  1499. int3 t1(t->pos + int3(-1,3,0)),
  1500. t2(t->pos + int3(-3,3,0));
  1501. if(map->isInTheMap(t1) && map->getTile(t1).tertype != TerrainTile::water
  1502. && (map->isInTheMap(t2) && map->getTile(t2).tertype != TerrainTile::water))
  1503. ret = 1; //lack of water
  1504. }
  1505. if(t->builtBuildings.find(ID)!=t->builtBuildings.end()) //already built
  1506. ret = 4;
  1507. return ret;
  1508. }
  1509. void CGameState::apply(CPack *pack)
  1510. {
  1511. ui16 typ = typeList.getTypeID(pack);
  1512. assert(typ >= 0);
  1513. applierGs->apps[typ]->applyOnGS(this,pack);
  1514. }
  1515. PlayerState * CGameState::getPlayer( ui8 color )
  1516. {
  1517. if(vstd::contains(players,color))
  1518. {
  1519. return &players[color];
  1520. }
  1521. else
  1522. {
  1523. tlog2 << "Warning: Cannot find info for player " << int(color) << std::endl;
  1524. return NULL;
  1525. }
  1526. }
  1527. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1528. {
  1529. if(!map->isInTheMap(src) || !map->isInTheMap(dest)) //check input
  1530. return false;
  1531. int3 hpos = hero->getPosition(false);
  1532. tribool blockLandSea; //true - blocks sea, false - blocks land, indeterminate - allows all
  1533. if (!hero->canWalkOnSea())
  1534. blockLandSea = (map->getTile(hpos).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1535. else
  1536. blockLandSea = boost::logic::indeterminate;
  1537. //graph initialization
  1538. std::vector< std::vector<CPathNode> > graph;
  1539. graph.resize(map->width);
  1540. for(size_t i=0; i<graph.size(); ++i)
  1541. {
  1542. graph[i].resize(map->height);
  1543. for(size_t j=0; j<graph[i].size(); ++j)
  1544. {
  1545. const TerrainTile *tinfo = &map->terrain[i][j][src.z];
  1546. CPathNode &node = graph[i][j];
  1547. node.accesible = !tinfo->blocked;
  1548. node.dist = -1;
  1549. node.theNodeBefore = NULL;
  1550. node.visited = false;
  1551. node.coord.x = i;
  1552. node.coord.y = j;
  1553. node.coord.z = dest.z;
  1554. if ((tinfo->tertype == TerrainTile::rock) //it's rock
  1555. || ((blockLandSea) && (tinfo->tertype == TerrainTile::water)) //it's sea and we cannot walk on sea
  1556. || ((!blockLandSea) && (tinfo->tertype != TerrainTile::water)) //it's land and we cannot walk on land
  1557. || !getPlayer(hero->tempOwner)->fogOfWarMap[i][j][src.z] //tile is covered by the FoW
  1558. )
  1559. {
  1560. node.accesible = false;
  1561. }
  1562. }
  1563. }
  1564. //Special rules for the destination tile
  1565. {
  1566. const TerrainTile *t = &map->terrain[dest.x][dest.y][dest.z];
  1567. CPathNode &d = graph[dest.x][dest.y];
  1568. //tile may be blocked by blockvis / normal vis obj but it still must be accessible
  1569. if(t->visitable)
  1570. {
  1571. d.accesible = true; //for allowing visiting objects
  1572. }
  1573. if(blockLandSea && t->tertype == TerrainTile::water) //hero can walk only on land and dst lays on the water
  1574. {
  1575. size_t i = 0;
  1576. for(; i < t->visitableObjects.size(); i++)
  1577. if(t->visitableObjects[i]->ID == 8) //it's a Boat
  1578. break;
  1579. d.accesible = (i < t->visitableObjects.size()); //dest is accessible only if there is boat
  1580. }
  1581. else if(!blockLandSea && t->tertype != TerrainTile::water) //hero is moving by water
  1582. {
  1583. d.accesible = (t->siodmyTajemniczyBajt & 64) && !t->blocked; //tile is accessible if it's coastal and not blocked
  1584. }
  1585. }
  1586. //graph initialized
  1587. //initial tile - set cost on 0 and add to the queue
  1588. graph[src.x][src.y].dist = 0;
  1589. std::queue<CPathNode> mq;
  1590. mq.push(graph[src.x][src.y]);
  1591. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1592. std::vector<int3> neighbours;
  1593. neighbours.reserve(8);
  1594. while(!mq.empty())
  1595. {
  1596. CPathNode &cp = graph[mq.front().coord.x][mq.front().coord.y];
  1597. mq.pop();
  1598. if (cp.coord == dest) //it's destination tile
  1599. {
  1600. if (cp.dist < curDist) //that path is better than previous one
  1601. curDist = cp.dist;
  1602. continue;
  1603. }
  1604. else
  1605. {
  1606. if (cp.dist > curDist) //it's not dest and current length is greater than cost of already found path
  1607. continue;
  1608. }
  1609. //add accessible neighbouring nodes to the queue
  1610. getNeighbours(cp.coord, neighbours, boost::logic::indeterminate);
  1611. for(unsigned int i=0; i < neighbours.size(); i++)
  1612. {
  1613. CPathNode & dp = graph[neighbours[i].x][neighbours[i].y];
  1614. if(dp.accesible)
  1615. {
  1616. int cost = getMovementCost(hero,cp.coord,dp.coord,hero->movement - cp.dist);
  1617. if((dp.dist==-1 || (dp.dist > cp.dist + cost)) && dp.accesible && checkForVisitableDir(cp.coord, dp.coord) && checkForVisitableDir(dp.coord, cp.coord))
  1618. {
  1619. dp.dist = cp.dist + cost;
  1620. dp.theNodeBefore = &cp;
  1621. mq.push(dp);
  1622. }
  1623. }
  1624. }
  1625. }
  1626. CPathNode *curNode = &graph[dest.x][dest.y];
  1627. if(!curNode->theNodeBefore) //destination is not accessible
  1628. return false;
  1629. //fill ret with found path
  1630. ret.nodes.clear();
  1631. while(curNode->coord != graph[src.x][src.y].coord)
  1632. {
  1633. ret.nodes.push_back(*curNode);
  1634. curNode = curNode->theNodeBefore;
  1635. }
  1636. ret.nodes.push_back(graph[src.x][src.y]);
  1637. return true;
  1638. }
  1639. bool CGameState::isVisible(int3 pos, int player)
  1640. {
  1641. if(player == 255) //neutral player
  1642. return false;
  1643. return players[player].fogOfWarMap[pos.x][pos.y][pos.z];
  1644. }
  1645. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  1646. {
  1647. if(player == 255) //neutral player
  1648. return false;
  1649. //object is visible when at least one blocked tile is visible
  1650. for(int fx=0; fx<8; ++fx)
  1651. {
  1652. for(int fy=0; fy<6; ++fy)
  1653. {
  1654. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  1655. if(map->isInTheMap(pos)
  1656. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  1657. && isVisible(pos, player) )
  1658. return true;
  1659. }
  1660. }
  1661. return false;
  1662. }
  1663. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1664. {
  1665. const TerrainTile * pom = &map->getTile(dst);
  1666. for(unsigned int b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  1667. {
  1668. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  1669. continue;
  1670. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  1671. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  1672. {
  1673. return false;
  1674. }
  1675. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  1676. {
  1677. return false;
  1678. }
  1679. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  1680. {
  1681. return false;
  1682. }
  1683. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  1684. {
  1685. return false;
  1686. }
  1687. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  1688. {
  1689. return false;
  1690. }
  1691. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  1692. {
  1693. return false;
  1694. }
  1695. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  1696. {
  1697. return false;
  1698. }
  1699. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  1700. {
  1701. return false;
  1702. }
  1703. }
  1704. return true;
  1705. }
  1706. int BattleInfo::calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting)
  1707. {
  1708. int attackDefenseBonus = attacker->Attack() - defender->Defense(),
  1709. minDmg = attacker->creature->damageMin * attacker->amount,
  1710. maxDmg = attacker->creature->damageMax * attacker->amount;
  1711. if(attacker->hasFeatureOfType(StackFeature::SIEGE_WEAPON)) //any siege weapon, but only ballista can attack
  1712. { //minDmg and maxDmg are multiplied by hero attack + 1
  1713. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  1714. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  1715. }
  1716. //calculating total attack/defense skills modifier
  1717. if(!shooting && attacker->hasFeatureOfType(StackFeature::ATTACK_BONUS, 0)) //bloodlust handling (etc.)
  1718. {
  1719. attackDefenseBonus += attacker->valOfFeatures(StackFeature::ATTACK_BONUS, 0);
  1720. }
  1721. if(shooting && attacker->hasFeatureOfType(StackFeature::ATTACK_BONUS, 1)) //precision handling (etc.)
  1722. {
  1723. attackDefenseBonus += attacker->valOfFeatures(StackFeature::ATTACK_BONUS, 1);
  1724. }
  1725. if(attacker->getEffect(55)) //slayer handling
  1726. {
  1727. std::vector<int> affectedIds;
  1728. switch(attacker->getEffect(55)->level)
  1729. {
  1730. case 3: //expert
  1731. {
  1732. affectedIds.push_back(40); //giant
  1733. affectedIds.push_back(41); //titan
  1734. affectedIds.push_back(152); //lord of thunder
  1735. } //continue adding ...
  1736. case 2: //advanced
  1737. {
  1738. affectedIds.push_back(12); //angel
  1739. affectedIds.push_back(13); //archangel
  1740. affectedIds.push_back(54); //devil
  1741. affectedIds.push_back(55); //arch devil
  1742. affectedIds.push_back(150); //supreme archangel
  1743. affectedIds.push_back(153); //antichrist
  1744. } //continue adding ...
  1745. case 0: case 1: //none and basic
  1746. {
  1747. affectedIds.push_back(26); //green dragon
  1748. affectedIds.push_back(27); //gold dragon
  1749. affectedIds.push_back(82); //red dragon
  1750. affectedIds.push_back(83); //black dragon
  1751. affectedIds.push_back(96); //behemot
  1752. affectedIds.push_back(97); //ancient behemot
  1753. affectedIds.push_back(110); //hydra
  1754. affectedIds.push_back(111); //chaos hydra
  1755. affectedIds.push_back(132); //azure dragon
  1756. affectedIds.push_back(133); //crystal dragon
  1757. affectedIds.push_back(134); //faerie dragon
  1758. affectedIds.push_back(135); //rust dragon
  1759. affectedIds.push_back(151); //diamond dragon
  1760. affectedIds.push_back(154); //blood dragon
  1761. affectedIds.push_back(155); //darkness dragon
  1762. affectedIds.push_back(156); //ghost behemot
  1763. affectedIds.push_back(157); //hell hydra
  1764. break;
  1765. }
  1766. }
  1767. for(unsigned int g=0; g<affectedIds.size(); ++g)
  1768. {
  1769. if(defender->creature->idNumber == affectedIds[g])
  1770. {
  1771. attackDefenseBonus += VLC->spellh->spells[55].powers[attacker->getEffect(55)->level];
  1772. break;
  1773. }
  1774. }
  1775. }
  1776. float dmgBonusMultiplier = 1.0f;
  1777. //bonus from attack/defense skills
  1778. if(attackDefenseBonus < 0) //decreasing dmg
  1779. {
  1780. if(0.02f * (-attackDefenseBonus) > 0.3f)
  1781. {
  1782. dmgBonusMultiplier += -0.3f;
  1783. }
  1784. else
  1785. {
  1786. dmgBonusMultiplier += 0.02f * attackDefenseBonus;
  1787. }
  1788. }
  1789. else //increasing dmg
  1790. {
  1791. if(0.05f * attackDefenseBonus > 4.0f)
  1792. {
  1793. dmgBonusMultiplier += 4.0f;
  1794. }
  1795. else
  1796. {
  1797. dmgBonusMultiplier += 0.05f * attackDefenseBonus;
  1798. }
  1799. }
  1800. //handling secondary abilities and artifacts giving premies to them
  1801. if(attackerHero)
  1802. {
  1803. if(shooting)
  1804. {
  1805. switch(attackerHero->getSecSkillLevel(1)) //archery
  1806. {
  1807. case 1: //basic
  1808. dmgBonusMultiplier *= 1.1f;
  1809. break;
  1810. case 2: //advanced
  1811. dmgBonusMultiplier *= 1.25f;
  1812. break;
  1813. case 3: //expert
  1814. dmgBonusMultiplier *= 1.5f;
  1815. break;
  1816. }
  1817. if(attackerHero->getSecSkillLevel(1) > 0) //non-none level
  1818. {
  1819. //apply artifact premy to archery
  1820. dmgBonusMultiplier *= (100.0f + attackerHero->valOfBonuses(HeroBonus::SECONDARY_SKILL_PREMY, 1)) / 100.0f;
  1821. }
  1822. }
  1823. else
  1824. {
  1825. switch(attackerHero->getSecSkillLevel(22)) //offense
  1826. {
  1827. case 1: //basic
  1828. dmgBonusMultiplier *= 1.1f;
  1829. break;
  1830. case 2: //advanced
  1831. dmgBonusMultiplier *= 1.2f;
  1832. break;
  1833. case 3: //expert
  1834. dmgBonusMultiplier *= 1.3f;
  1835. break;
  1836. }
  1837. }
  1838. }
  1839. if(defendingHero)
  1840. {
  1841. switch(defendingHero->getSecSkillLevel(23)) //armorer
  1842. {
  1843. case 1: //basic
  1844. dmgBonusMultiplier *= 0.95f;
  1845. break;
  1846. case 2: //advanced
  1847. dmgBonusMultiplier *= 0.9f;
  1848. break;
  1849. case 3: //expert
  1850. dmgBonusMultiplier *= 0.85f;
  1851. break;
  1852. }
  1853. }
  1854. //handling spell effects
  1855. if(!shooting && defender->hasFeatureOfType(StackFeature::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  1856. {
  1857. dmgBonusMultiplier *= float(defender->valOfFeatures(StackFeature::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0f;
  1858. }
  1859. else if(shooting && defender->hasFeatureOfType(StackFeature::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  1860. {
  1861. dmgBonusMultiplier *= float(defender->valOfFeatures(StackFeature::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0f;
  1862. }
  1863. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  1864. {
  1865. dmgBonusMultiplier *= 0.8f * float(VLC->spellh->spells[42].powers[attacker->getEffect(42)->level]); //the second factor is 1 or 0
  1866. }
  1867. minDmg *= dmgBonusMultiplier;
  1868. maxDmg *= dmgBonusMultiplier;
  1869. if(attacker->getEffect(42)) //curse handling (rest)
  1870. {
  1871. minDmg -= VLC->spellh->spells[42].powers[attacker->getEffect(42)->level];
  1872. return minDmg;
  1873. }
  1874. else if(attacker->getEffect(41)) //bless handling
  1875. {
  1876. maxDmg += VLC->spellh->spells[41].powers[attacker->getEffect(41)->level];
  1877. return maxDmg;
  1878. }
  1879. else
  1880. {
  1881. if(minDmg != maxDmg)
  1882. return minDmg + rand() % (maxDmg - minDmg + 1);
  1883. else
  1884. return minDmg;
  1885. }
  1886. tlog1 << "We are too far in calculateDmg...\n";
  1887. return -1;
  1888. }
  1889. void BattleInfo::calculateCasualties( std::set<std::pair<ui32,si32> > *casualties )
  1890. {
  1891. for(unsigned int i=0; i<stacks.size();i++)//setting casualties
  1892. {
  1893. if(!stacks[i]->alive())
  1894. {
  1895. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount));
  1896. }
  1897. else if(stacks[i]->amount != stacks[i]->baseAmount)
  1898. {
  1899. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount - stacks[i]->amount));
  1900. }
  1901. }
  1902. }
  1903. si8 CGameState::battleMaxSpellLevel()
  1904. {
  1905. if(!curB) //there is not battle
  1906. {
  1907. tlog1 << "si8 CGameState::maxSpellLevel() call when there is no battle!" << std::endl;
  1908. throw "si8 CGameState::maxSpellLevel() call when there is no battle!";
  1909. }
  1910. si8 levelLimit = SPELL_LEVELS;
  1911. const CGHeroInstance *h1 = getHero(curB->hero1);
  1912. if(h1)
  1913. {
  1914. for(std::list<HeroBonus>::const_iterator i = h1->bonuses.begin(); i != h1->bonuses.end(); i++)
  1915. if(i->type == HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL)
  1916. amin(levelLimit, i->val);
  1917. }
  1918. const CGHeroInstance *h2 = getHero(curB->hero2);
  1919. if(h2)
  1920. {
  1921. for(std::list<HeroBonus>::const_iterator i = h2->bonuses.begin(); i != h2->bonuses.end(); i++)
  1922. if(i->type == HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL)
  1923. amin(levelLimit, i->val);
  1924. }
  1925. return levelLimit;
  1926. }
  1927. std::set<CStack*> BattleInfo::getAttackedCreatures(const CSpell * s, const CGHeroInstance * caster, int destinationTile)
  1928. {
  1929. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, caster->getSpellSchoolLevel(s));
  1930. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurences of two hex creatures*/
  1931. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  1932. if(s->id == 24 || s->id == 25 || s->id == 26) //death ripple, destroy undead and armageddon
  1933. {
  1934. for(int it=0; it<stacks.size(); ++it)
  1935. {
  1936. if((s->id == 24 && !stacks[it]->creature->isUndead()) //death ripple
  1937. || (s->id == 25 && stacks[it]->creature->isUndead()) //destroy undead
  1938. || (s->id == 26) //armageddon
  1939. )
  1940. {
  1941. attackedCres.insert(stacks[it]);
  1942. }
  1943. }
  1944. }
  1945. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_1") != std::string::npos
  1946. || VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_2") != std::string::npos) //spell to be cast on a specific creature but massive on expert
  1947. {
  1948. if(caster->getSpellSchoolLevel(s) < 3) /*not expert */
  1949. {
  1950. CStack * st = getStackT(destinationTile, onlyAlive);
  1951. if(st)
  1952. attackedCres.insert(st);
  1953. }
  1954. else
  1955. {
  1956. for(int it=0; it<stacks.size(); ++it)
  1957. {
  1958. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  1959. if((VLC->spellh->spells[s->id].positiveness >= 0 && stacks[it]->owner == caster->tempOwner)
  1960. ||(VLC->spellh->spells[s->id].positiveness <= 0 && stacks[it]->owner != caster->tempOwner )
  1961. )
  1962. {
  1963. if(!onlyAlive || stacks[it]->alive())
  1964. attackedCres.insert(stacks[it]);
  1965. }
  1966. }
  1967. } //if(caster->getSpellSchoolLevel(s) < 3)
  1968. }
  1969. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET") != std::string::npos) //spell to be cast on one specific creature
  1970. {
  1971. CStack * st = getStackT(destinationTile, onlyAlive);
  1972. if(st)
  1973. attackedCres.insert(st);
  1974. }
  1975. else //custom range from attackedHexes
  1976. {
  1977. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  1978. {
  1979. CStack * st = getStackT(*it, onlyAlive);
  1980. if(st)
  1981. attackedCres.insert(st);
  1982. }
  1983. }
  1984. return attackedCres;
  1985. }
  1986. int BattleInfo::calculateSpellDuration(const CSpell * spell, const CGHeroInstance * caster)
  1987. {
  1988. switch(spell->id)
  1989. {
  1990. case 56: //frenzy
  1991. return 1;
  1992. default: //other spells
  1993. return caster->getPrimSkillLevel(2) + caster->valOfBonuses(HeroBonus::SPELL_DURATION);
  1994. }
  1995. }
  1996. CStack * BattleInfo::generateNewStack(const CGHeroInstance * owner, int creatureID, int amount, int stackID, bool attackerOwned, int slot, int /*TerrainTile::EterrainType*/ terrain, int position)
  1997. {
  1998. CStack * ret = new CStack(&VLC->creh->creatures[creatureID], amount, owner ? owner->tempOwner : 255, stackID, attackerOwned, slot);
  1999. if(owner)
  2000. {
  2001. ret->features.push_back(makeFeature(StackFeature::SPEED_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->valOfBonuses(HeroBonus::STACKS_SPEED), StackFeature::BONUS_FROM_HERO));
  2002. //base luck/morale calculations
  2003. ret->morale = owner->getCurrentMorale(slot, false);
  2004. ret->luck = owner->getCurrentLuck(slot, false);
  2005. //other bonuses
  2006. ret->features.push_back(makeFeature(StackFeature::ATTACK_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->getPrimSkillLevel(0), StackFeature::BONUS_FROM_HERO));
  2007. ret->features.push_back(makeFeature(StackFeature::DEFENCE_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->getPrimSkillLevel(1), StackFeature::BONUS_FROM_HERO));
  2008. ret->features.push_back(makeFeature(StackFeature::HP_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->valOfBonuses(HeroBonus::STACK_HEALTH), StackFeature::BONUS_FROM_HERO));
  2009. ret->firstHPleft = ret->MaxHealth();
  2010. }
  2011. else
  2012. {
  2013. ret->morale = 0;
  2014. ret->luck = 0;
  2015. }
  2016. //native terrain bonuses
  2017. int faction = ret->creature->faction;
  2018. if(faction >= 0 && VLC->heroh->nativeTerrains[faction] == terrain)
  2019. {
  2020. ret->features.push_back(makeFeature(StackFeature::SPEED_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2021. ret->features.push_back(makeFeature(StackFeature::ATTACK_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2022. ret->features.push_back(makeFeature(StackFeature::DEFENCE_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2023. }
  2024. ret->position = position;
  2025. return ret;
  2026. }
  2027. CStack * BattleInfo::getNextStack()
  2028. {
  2029. CStack *current = getStack(activeStack);
  2030. for (unsigned int i = 0; i < stacks.size(); i++) //find fastest not moved/waited stack (stacks vector is sorted by speed)
  2031. {
  2032. if(stacks[i]->willMove() && !vstd::contains(stacks[i]->state,WAITING))
  2033. return stacks[i];
  2034. }
  2035. for (int i = stacks.size() - 1; i >= 0 ; i--) //find slowest waiting stack
  2036. {
  2037. if(stacks[i]->willMove())
  2038. return stacks[i];
  2039. }
  2040. return NULL; //all stacks moved or defending!
  2041. }
  2042. std::vector<CStack> BattleInfo::getStackQueue()
  2043. {
  2044. std::vector<CStack> ret;
  2045. std::vector<int> taken; //if non-zero value, corresponding stack has been placed in ret
  2046. taken.resize(stacks.size());
  2047. for(unsigned int g=0; g<taken.size(); ++g)
  2048. {
  2049. taken[g] = 0;
  2050. }
  2051. 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
  2052. {
  2053. for(unsigned int gc=0; gc<stacks.size(); ++gc)
  2054. {
  2055. int id = -1, speed = -1;
  2056. for(unsigned int i=0; i<stacks.size(); ++i) //find not waited stacks only
  2057. {
  2058. if((moved == 1 ||!vstd::contains(stacks[i]->state, DEFENDING))
  2059. && stacks[i]->alive()
  2060. && (moved == 1 || !vstd::contains(stacks[i]->state, MOVED))
  2061. && !vstd::contains(stacks[i]->state,WAITING)
  2062. && taken[i]==0
  2063. && !stacks[i]->hasFeatureOfType(StackFeature::NOT_ACTIVE)) //eg. Ammo Cart
  2064. {
  2065. if(speed == -1 || stacks[i]->Speed() > speed)
  2066. {
  2067. id = i;
  2068. speed = stacks[i]->Speed();
  2069. }
  2070. }
  2071. }
  2072. if(id != -1)
  2073. {
  2074. ret.push_back(*stacks[id]);
  2075. taken[id] = 1;
  2076. }
  2077. else //choose something from not moved stacks
  2078. {
  2079. int id = -1, speed = 10000; //infinite speed
  2080. for(unsigned int i=0; i<stacks.size(); ++i) //find waited stacks only
  2081. {
  2082. if((moved == 1 ||!vstd::contains(stacks[i]->state, DEFENDING))
  2083. && stacks[i]->alive()
  2084. && (moved == 1 || !vstd::contains(stacks[i]->state, MOVED))
  2085. && vstd::contains(stacks[i]->state,WAITING)
  2086. && taken[i]==0
  2087. && !stacks[i]->hasFeatureOfType(StackFeature::NOT_ACTIVE)) //eg. Ammo Cart
  2088. {
  2089. if(stacks[i]->Speed() < speed) //slowest one
  2090. {
  2091. id = i;
  2092. speed = stacks[i]->Speed();
  2093. }
  2094. }
  2095. }
  2096. if(id != -1)
  2097. {
  2098. ret.push_back(*stacks[id]);
  2099. taken[id] = 1;
  2100. }
  2101. else
  2102. {
  2103. break; //no stacks have been found, so none of them will be found in next iterations
  2104. }
  2105. }
  2106. }
  2107. }
  2108. return ret;
  2109. }
  2110. int3 CPath::startPos() const
  2111. {
  2112. return nodes[nodes.size()-1].coord;
  2113. }
  2114. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  2115. {
  2116. if (mode==0)
  2117. {
  2118. for (unsigned int i=0;i<nodes.size();i++)
  2119. {
  2120. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2121. }
  2122. }
  2123. }
  2124. int3 CPath::endPos() const
  2125. {
  2126. return nodes[0].coord;
  2127. }