CGameState.cpp 61 KB

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