CGameState.cpp 69 KB

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